Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { getDateFnsLocale, getLocaleWeekStartsOn } from "./date-fns";
describe("date-fns locale bridge", () => {
it("maps supported app locales to date-fns locales", () => {
expect(getDateFnsLocale("de").code).toBe("de");
expect(getDateFnsLocale("de-DE").code).toBe("de");
expect(getDateFnsLocale("en").code).toBe("en-US");
expect(getDateFnsLocale("en-US").code).toBe("en-US");
});
it("keeps week starts aligned with the active locale", () => {
expect(getLocaleWeekStartsOn("de")).toBe(1);
expect(getLocaleWeekStartsOn("en")).toBe(0);
expect(getLocaleWeekStartsOn(undefined)).toBe(1);
});
});
@@ -0,0 +1,12 @@
import { de, enUS } from "date-fns/locale";
type WeekStartsOn = 0 | 1 | 2 | 3 | 4 | 5 | 6;
export function getDateFnsLocale(language?: string) {
const locale = language?.toLowerCase().split("-")[0];
return locale === "en" ? enUS : de;
}
export function getLocaleWeekStartsOn(language?: string): WeekStartsOn {
return (getDateFnsLocale(language).options?.weekStartsOn ?? 1) as WeekStartsOn;
}
@@ -0,0 +1,64 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import {
formatCurrency,
formatDate,
formatNumber,
formatRelativeDate,
formatRelativeTime,
} from "./format";
describe("locale formatters", () => {
afterEach(() => {
vi.restoreAllMocks();
});
test("reuses number formatters for repeated locale and option combinations", () => {
const constructorSpy = vi.spyOn(Intl, "NumberFormat");
expect(formatNumber(1_234.5, "en-US", { maximumFractionDigits: 1 })).toBe("1,234.5");
expect(formatNumber(9_876.5, "en-US", { maximumFractionDigits: 1 })).toBe("9,876.5");
expect(constructorSpy).toHaveBeenCalledTimes(1);
});
test("keeps separate number formatters for different options", () => {
const constructorSpy = vi.spyOn(Intl, "NumberFormat");
expect(formatNumber(1_234.5, "en-US", { minimumFractionDigits: 3 })).toBe("1,234.500");
expect(formatNumber(1_234.5, "en-US", { minimumFractionDigits: 4 })).toBe("1,234.5000");
expect(constructorSpy).toHaveBeenCalledTimes(2);
});
test("reuses currency formatter instances", () => {
const constructorSpy = vi.spyOn(Intl, "NumberFormat");
expect(formatCurrency(42, "USD", "en-US")).toBe("$42.00");
expect(formatCurrency(99, "USD", "en-US")).toBe("$99.00");
expect(constructorSpy).toHaveBeenCalledTimes(1);
});
test("reuses date-time formatters for repeated locale and options", () => {
const constructorSpy = vi.spyOn(Intl, "DateTimeFormat");
const options: Intl.DateTimeFormatOptions = { dateStyle: "medium", timeZone: "UTC" };
expect(formatDate("2026-05-27T10:30:00.000Z", "en-US", options)).toBe("May 27, 2026");
expect(formatDate("2026-05-28T10:30:00.000Z", "en-US", options)).toBe("May 28, 2026");
expect(constructorSpy).toHaveBeenCalledTimes(1);
});
test("preserves relative date output", () => {
const relativeTo = new Date("2026-05-27T10:00:00.000Z");
expect(formatRelativeDate("2026-05-26T10:00:00.000Z", "en-US", { relativeTo })).toBe("yesterday");
expect(formatRelativeDate("2026-05-28T10:00:00.000Z", "en-US", { relativeTo })).toBe("tomorrow");
});
test("preserves relative time output", () => {
expect(formatRelativeTime(-2, "day", "en-US")).toBe("2 days ago");
expect(formatRelativeTime(3, "hour", "en-US")).toBe("in 3 hours");
});
});
@@ -0,0 +1,136 @@
import { useTranslation } from "react-i18next";
import { defaultLocale, type SupportedLocale } from "./i18n";
// Locale-aware Intl wrappers. Server code calls the pure functions with an
// explicit locale (resolved by getTranslations); client React code uses the
// useLocaleFormatters() hook which reads the active language from i18next.
const numberFormatters = new Map<string, Intl.NumberFormat>();
const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();
const relativeTimeFormatters = new Map<string, Intl.RelativeTimeFormat>();
function formatterKey(locale: SupportedLocale | string | undefined, options?: Record<string, unknown>): string {
return `${locale ?? defaultLocale}:${JSON.stringify(options ?? {})}`;
}
function getNumberFormatter(locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): Intl.NumberFormat {
const key = formatterKey(locale, options as Record<string, unknown> | undefined);
const cached = numberFormatters.get(key);
if (cached) return cached;
const formatter = new Intl.NumberFormat(locale ?? defaultLocale, options);
numberFormatters.set(key, formatter);
return formatter;
}
function getDateTimeFormatter(locale: SupportedLocale | string, options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {
const key = formatterKey(locale, options as Record<string, unknown> | undefined);
const cached = dateTimeFormatters.get(key);
if (cached) return cached;
const formatter = new Intl.DateTimeFormat(locale ?? defaultLocale, options);
dateTimeFormatters.set(key, formatter);
return formatter;
}
function getRelativeTimeFormatter(locale: SupportedLocale | string, options?: Intl.RelativeTimeFormatOptions): Intl.RelativeTimeFormat {
const key = formatterKey(locale, options as Record<string, unknown> | undefined);
const cached = relativeTimeFormatters.get(key);
if (cached) return cached;
const formatter = new Intl.RelativeTimeFormat(locale ?? defaultLocale, options);
relativeTimeFormatters.set(key, formatter);
return formatter;
}
export function formatNumber(value: number, locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): string {
return getNumberFormatter(locale, options).format(value);
}
export function formatCurrency(value: number, currency: string, locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): string {
return getNumberFormatter(locale, { style: "currency", currency, ...options }).format(value);
}
export function formatCurrencyFromCents(cents: number, currency: string, locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): string {
return formatCurrency(cents / 100, currency, locale, options);
}
export function formatPercent(value: number, locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): string {
return getNumberFormatter(locale, { style: "percent", ...options }).format(value);
}
export function formatCompactNumber(value: number, locale: SupportedLocale | string, options?: Intl.NumberFormatOptions): string {
return getNumberFormatter(locale, { notation: "compact", ...options }).format(value);
}
export function formatDate(value: Date | number | string, locale: SupportedLocale | string, options?: Intl.DateTimeFormatOptions): string {
const date = value instanceof Date ? value : new Date(value);
return getDateTimeFormatter(locale, options).format(date);
}
export function formatDateTime(value: Date | number | string, locale: SupportedLocale | string, options?: Intl.DateTimeFormatOptions): string {
return formatDate(value, locale, { dateStyle: "medium", timeStyle: "short", ...options });
}
export function formatRelativeTime(
value: number,
unit: Intl.RelativeTimeFormatUnit,
locale: SupportedLocale | string,
options?: Intl.RelativeTimeFormatOptions
): string {
return getRelativeTimeFormatter(locale, options).format(value, unit);
}
export function formatRelativeDate(
value: Date | number | string,
locale: SupportedLocale | string,
options?: Intl.RelativeTimeFormatOptions & { relativeTo?: Date | number }
): string {
const date = value instanceof Date ? value.getTime() : new Date(value).getTime();
const relativeTo = options?.relativeTo instanceof Date ? options.relativeTo.getTime() : (options?.relativeTo ?? Date.now());
const delta = date - relativeTo;
const units: Array<{ unit: Intl.RelativeTimeFormatUnit; ms: number }> = [
{ unit: "year", ms: 365.25 * 24 * 60 * 60 * 1000 },
{ unit: "month", ms: 30 * 24 * 60 * 60 * 1000 },
{ unit: "day", ms: 24 * 60 * 60 * 1000 },
{ unit: "hour", ms: 60 * 60 * 1000 },
{ unit: "minute", ms: 60 * 1000 },
{ unit: "second", ms: 1000 },
];
const formatterOptions = { ...(options ?? {}) };
delete formatterOptions.relativeTo;
const formatter = getRelativeTimeFormatter(locale, { numeric: "auto", ...formatterOptions });
const unit = units.find((item) => Math.abs(delta) >= item.ms) ?? units[units.length - 1];
return formatter.format(Math.round(delta / unit.ms), unit.unit);
}
export type LocaleFormatters = {
locale: string;
number: (value: number, options?: Intl.NumberFormatOptions) => string;
currency: (value: number, currency: string, options?: Intl.NumberFormatOptions) => string;
currencyFromCents: (cents: number, currency: string, options?: Intl.NumberFormatOptions) => string;
percent: (value: number, options?: Intl.NumberFormatOptions) => string;
compact: (value: number, options?: Intl.NumberFormatOptions) => string;
date: (value: Date | number | string, options?: Intl.DateTimeFormatOptions) => string;
dateTime: (value: Date | number | string, options?: Intl.DateTimeFormatOptions) => string;
relativeTime: (value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions) => string;
relativeDate: (value: Date | number | string, options?: Intl.RelativeTimeFormatOptions & { relativeTo?: Date | number }) => string;
};
export function createLocaleFormatters(locale: SupportedLocale | string): LocaleFormatters {
return {
locale,
number: (value, options) => formatNumber(value, locale, options),
currency: (value, currency, options) => formatCurrency(value, currency, locale, options),
currencyFromCents: (cents, currency, options) => formatCurrencyFromCents(cents, currency, locale, options),
percent: (value, options) => formatPercent(value, locale, options),
compact: (value, options) => formatCompactNumber(value, locale, options),
date: (value, options) => formatDate(value, locale, options),
dateTime: (value, options) => formatDateTime(value, locale, options),
relativeTime: (value, unit, options) => formatRelativeTime(value, unit, locale, options),
relativeDate: (value, options) => formatRelativeDate(value, locale, options),
};
}
export function useLocaleFormatters(): LocaleFormatters {
const { i18n } = useTranslation();
const locale = (i18n?.language ?? defaultLocale) as SupportedLocale | string;
return createLocaleFormatters(locale);
}
@@ -0,0 +1,2 @@
export { defaultLocale, getDirection, i18nConfig, i18nNamespaces, isRTL, isSupportedLocale, supportedLocales } from "@toolctrl/i18n";
export type { I18nNamespace, SupportedLocale, TextDirection } from "@toolctrl/i18n";
@@ -0,0 +1,30 @@
import { describe, expect, test } from "vitest";
import i18next from "i18next";
import { ensureServerGlobalI18n, syncServerGlobalI18nLanguage } from "./i18next.global.server";
describe("server global i18next bootstrap", () => {
test("initialises the global instance with preloaded resources", async () => {
await ensureServerGlobalI18n();
expect(i18next.isInitialized).toBe(true);
// The sidebar toggle label is the canonical string that previously rendered
// empty during SSR (causing button-name a11y failures + hydration #418).
expect(i18next.t("components.sidebar.toggle")).not.toBe("");
expect(i18next.t("components.sidebar.toggle")).not.toBe("components.sidebar.toggle");
});
test("aligns the global language with the requested locale", async () => {
await syncServerGlobalI18nLanguage("en");
expect(i18next.language).toBe("en");
const en = i18next.t("components.sidebar.toggle");
await syncServerGlobalI18nLanguage("de");
expect(i18next.language).toBe("de");
const de = i18next.t("components.sidebar.toggle");
expect(en).not.toBe("");
expect(de).not.toBe("");
expect(de).not.toBe(en);
});
});
@@ -0,0 +1,93 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import i18next, { type Resource, type ResourceLanguage } from "i18next";
import { i18nConfig, i18nNamespaces, supportedLocales } from "./i18n";
import { serverLocalePath } from "./i18next.server";
/**
* Server-side bootstrap for the *global* i18next instance (the default export
* of `i18next`). A large number of components resolve translations through the
* module-level `t` helper (`import { t } from "i18next"`) rather than the
* `useTranslation()` hook. On the client that global instance is initialised in
* `entry.client.tsx`, but on the server only the per-request scoped instance was
* ever initialised. That left the global `t` returning empty strings during SSR,
* which produced empty `sr-only` labels (axe `button-name`/`link-name`
* violations) and — more damagingly — React hydration mismatches (error #418)
* that aborted hydration and broke client interactivity on authenticated pages.
*
* Initialising the global instance with every locale preloaded synchronously,
* then aligning its language with the request locale immediately before the
* (synchronous) shell render, keeps SSR output identical to the hydrated client
* output. The language is mutated per request; because the non-streaming shell
* render that follows `syncServerGlobalI18nLanguage` is synchronous, the global
* language is correct for that render.
*/
function loadAllResources(): Resource {
const resources: Resource = {};
for (const locale of supportedLocales) {
const bundle: ResourceLanguage = {};
for (const namespace of i18nNamespaces) {
try {
const file = path.join(serverLocalePath, locale, `${namespace}.json`);
bundle[namespace] = JSON.parse(readFileSync(file, "utf8")) as ResourceLanguage[string];
} catch {
// A missing namespace file is non-fatal: i18next will fall back to the
// fallback language / key for that namespace.
bundle[namespace] = {};
}
}
resources[locale] = bundle;
}
return resources;
}
function registerAllBundles(resources: Resource): void {
// Register every locale/namespace bundle. `init({ resources })` only
// guarantees the active language's bundle is added; registering them all
// up-front lets `changeLanguage` resolve any supported locale synchronously.
// This also backfills bundles when another module (e.g. test setup) already
// initialised the global instance with a narrower resource set.
for (const locale of Object.keys(resources)) {
for (const namespace of Object.keys(resources[locale]!)) {
if (!i18next.hasResourceBundle(locale, namespace)) {
i18next.addResourceBundle(locale, namespace, resources[locale]![namespace], true, true);
}
}
}
}
let initPromise: Promise<typeof i18next> | null = null;
export async function ensureServerGlobalI18n(): Promise<typeof i18next> {
if (i18next.isInitialized) {
registerAllBundles(loadAllResources());
return i18next;
}
if (!initPromise) {
const resources = loadAllResources();
initPromise = i18next
.init({
...i18nConfig,
lng: i18nConfig.fallbackLng,
preload: [...supportedLocales],
resources,
// Resources are bundled in memory, so no backend/async loading is needed.
initImmediate: false,
})
.then(() => {
registerAllBundles(resources);
return i18next;
});
}
return initPromise;
}
export async function syncServerGlobalI18nLanguage(language: string): Promise<void> {
await ensureServerGlobalI18n();
if (i18next.language !== language) {
await i18next.changeLanguage(language);
}
}
@@ -0,0 +1,97 @@
// @vitest-environment node
import { describe, expect, it, vi } from "vitest";
type TestWebConfig = {
nodeEnv: string;
sessionSecret: string;
routing: {
appBaseDomain: string;
protocol: "http" | "https";
};
};
const testWebConfig: TestWebConfig = {
nodeEnv: "production",
sessionSecret: "production-session-secret-with-enough-entropy",
routing: {
appBaseDomain: "example.com",
protocol: "https",
},
};
vi.doMock("@toolctrl/config", async () => {
const actual = await vi.importActual<typeof import("@toolctrl/config")>("@toolctrl/config");
return {
...actual,
loadRequiredWebConfig: () => testWebConfig,
};
});
async function importI18nextServerWithConfig(config: typeof testWebConfig) {
Object.assign(testWebConfig, config);
vi.resetModules();
return await import("./i18next.server");
}
describe("i18n cookie policy", () => {
it("resolves locale files from the workspace path when running from a bundled server file", async () => {
const { resolveServerLocalePath } = await importI18nextServerWithConfig(testWebConfig);
const resolved = resolveServerLocalePath({
moduleUrl: "file:///myapp/apps/web/build/server/assets/server-build.js",
cwd: "/myapp",
exists: (candidate) => candidate === "/myapp/apps/web/public/locales",
});
expect(resolved).toBe("/myapp/apps/web/public/locales");
});
it("keeps source-relative locale resolution for local source execution", async () => {
const { resolveServerLocalePath } = await importI18nextServerWithConfig(testWebConfig);
const resolved = resolveServerLocalePath({
moduleUrl: "file:///repo/apps/web/app/locale/i18next.server.ts",
cwd: "/repo",
exists: (candidate) => candidate === "/repo/apps/web/public/locales",
});
expect(resolved).toBe("/repo/apps/web/public/locales");
});
it("serializes hardened production i18n cookie attributes without exposing the session secret", async () => {
const productionSecret = "production-session-secret-with-enough-entropy";
const { i18nCookie } = await importI18nextServerWithConfig({
nodeEnv: "production",
sessionSecret: productionSecret,
routing: {
appBaseDomain: "example.com",
protocol: "https",
},
});
const header = await i18nCookie.serialize("de");
expect(header).toContain("_i18n=");
expect(header).toContain("Domain=example.com");
expect(header).toContain("SameSite=Lax");
expect(header).toContain("Secure");
expect(header).toContain("HttpOnly");
expect(header).toContain("Path=/");
expect(header).not.toContain(productionSecret);
});
it("keeps local i18n cookies domainless", async () => {
const { i18nCookie } = await importI18nextServerWithConfig({
nodeEnv: "test",
sessionSecret: "local-session-secret-with-enough-entropy",
routing: {
appBaseDomain: "localhost",
protocol: "http",
},
});
const header = await i18nCookie.serialize("de");
expect(header).toContain("_i18n=");
expect(header).not.toContain("Domain=");
expect(header).not.toContain("Secure");
});
});
@@ -0,0 +1,80 @@
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createCookie } from "react-router";
import { loadRequiredWebConfig, resolveSessionCookiePolicy } from "@toolctrl/config";
import { RemixI18Next } from "remix-i18next/server";
import { i18nConfig, i18nNamespaces } from "./i18n";
import Backend from "i18next-fs-backend";
const webConfig = loadRequiredWebConfig();
type ResolveServerLocalePathOptions = {
moduleUrl?: string;
cwd?: string;
exists?: (candidate: string) => boolean;
};
export function resolveServerLocalePath({ moduleUrl = import.meta.url, cwd = process.cwd(), exists = existsSync }: ResolveServerLocalePathOptions = {}) {
// `path.resolve(path.dirname(fileURLToPath(url)), "../../...")` instead
// of `new URL("...", moduleUrl)` because vitest 3 resolves relative
// URL constructors through the Vite dev server (returning http://...);
// we need a file path here.
const moduleDir = path.dirname(fileURLToPath(moduleUrl));
const candidates = [
path.resolve(moduleDir, "../../public/locales"),
path.resolve(cwd, "apps/web/public/locales"),
path.resolve(cwd, "public/locales"),
];
return candidates.find((candidate) => exists(candidate)) ?? candidates[0];
}
export const serverLocalePath = resolveServerLocalePath();
export const i18nCookie = createCookie("_i18n", {
...resolveSessionCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
maxAge: 60 * 60 * 24 * 30,
}),
secrets: webConfig.sessionSecret ? [webConfig.sessionSecret] : [],
});
export const remixI18Next = new RemixI18Next({
detection: {
// The cookie used to store user's language preference.
cookie: i18nCookie,
// The supported languages.
supportedLanguages: i18nConfig.supportedLngs,
// The fallback language.
fallbackLanguage: i18nConfig.fallbackLng,
},
// The i18next configuration used when translating
// Server-Side only messages.
i18next: {
...i18nConfig,
backend: {
localePath: serverLocalePath,
loadPath: `${serverLocalePath}/{{lng}}/{{ns}}.json`,
},
},
// The plugins you want RemixI18next to use for `i18n.getFixedT` inside loaders and actions.
// E.g. The Backend plugin for loading translations from the file system.
plugins: [Backend],
});
export async function getTranslations(request: Request, namespace = "translations") {
// Load every namespace so callers can resolve cross-namespace keys like
// `t("auth:errors.invalidEmail")` while `namespace` stays the default for
// un-prefixed keys. See #72 i18n namespace split.
const namespaces: [string, ...string[]] = [namespace, ...i18nNamespaces.filter((ns) => ns !== namespace)];
const t = await remixI18Next.getFixedT(request, namespaces);
let translations: any = {};
const locale = await remixI18Next.getLocale(request);
return { t, translations, locale };
}
@@ -0,0 +1,51 @@
import { defaultLocale, isSupportedLocale } from "@toolctrl/i18n";
import { remixI18Next } from "./i18next.server";
/**
* Mail-side translator function. Kept locally now that the legacy
* `@toolctrl/mail` template-string renderer is retired; the React-Email
* templates do not consume a translator directly, but this signature is
* still exposed for downstream callers that audit/log under translator
* context.
*/
export type MailTranslator = (key: string, vars?: Record<string, unknown>) => string;
const MAIL_NAMESPACE = "mail" as const;
/**
* Normalize a (possibly null/unsupported) locale string to a supported locale,
* falling back to {@link defaultLocale} when no supported match is found.
*/
export function resolveMailLocale(locale: string | null | undefined): string {
if (locale && isSupportedLocale(locale)) {
return locale;
}
return defaultLocale;
}
/**
* Return a {@link MailTranslator} bound to the given user locale, backed by the
* `mail` i18next namespace (loaded from `apps/web/public/locales/<locale>/mail.json`).
*/
export async function getMailTranslator(locale: string | null | undefined): Promise<{
t: MailTranslator;
locale: string;
}> {
const resolved = resolveMailLocale(locale);
const fixedT = await remixI18Next.getFixedT(resolved, MAIL_NAMESPACE);
const t: MailTranslator = (key, vars) => fixedT(key, vars ?? {}) as string;
return { t, locale: resolved };
}
/**
* Convenience helper that derives the mail translator from a Request — used
* when the caller does not yet have a user record (e.g. pre-registration, anonymous
* password reset, anonymous invitation acceptance).
*/
export async function getMailTranslatorFromRequest(request: Request): Promise<{
t: MailTranslator;
locale: string;
}> {
const detected = await remixI18Next.getLocale(request);
return getMailTranslator(detected);
}