Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

7.6 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import { getLocale } from "./locale-store";
import { en } from "./locales/en";
import type { InterpolationValues, MessageKey, MessageTree } from "./types";

export const LOCALES = {
  en: { label: "English", nativeLabel: "English" },
  "zh-CN": { label: "Chinese (Simplified)", nativeLabel: "简体中文" },
  "zh-TW": {
    label: "Chinese (Traditional, Taiwan)",
    nativeLabel: "繁體中文(台灣)",
  },
  ja: { label: "Japanese", nativeLabel: "日本語" },
  ko: { label: "Korean", nativeLabel: "한국어" },
  es: { label: "Spanish (Spain)", nativeLabel: "Español (España)" },
  "es-419": {
    label: "Spanish (Latin America)",
    nativeLabel: "Español (Latinoamérica)",
  },
  "pt-BR": { label: "Portuguese (Brazil)", nativeLabel: "Português (Brasil)" },
  fr: { label: "French", nativeLabel: "Français" },
  de: { label: "German", nativeLabel: "Deutsch" },
  it: { label: "Italian", nativeLabel: "Italiano" },
  ru: { label: "Russian", nativeLabel: "Русский" },
  sv: { label: "Swedish", nativeLabel: "Svenska" },
  hi: { label: "Hindi", nativeLabel: "हिन्दी" },
  ar: { label: "Arabic", nativeLabel: "العربية" },
  he: { label: "Hebrew", nativeLabel: "עברית" },
  id: { label: "Indonesian", nativeLabel: "Bahasa Indonesia" },
  vi: { label: "Vietnamese", nativeLabel: "Tiếng Việt" },
  tr: { label: "Turkish", nativeLabel: "Türkçe" },
  pl: { label: "Polish", nativeLabel: "Polski" },
  uk: { label: "Ukrainian", nativeLabel: "Українська" },
  th: { label: "Thai", nativeLabel: "ไทย" },
  fa: { label: "Persian", nativeLabel: "فارسی" },
  cs: { label: "Czech", nativeLabel: "Čeština" },
  nl: { label: "Dutch", nativeLabel: "Nederlands" },
} as const;

export type Locale = keyof typeof LOCALES;
export type TranslationKey = MessageKey<typeof en>;

const loadedMessages: Partial<Record<Locale, MessageTree>> = {
  en,
};
export const messages = loadedMessages as typeof loadedMessages & {
  en: typeof en;
};

type LazyLocale = Exclude<Locale, "en">;

const localeLoaders: Record<LazyLocale, () => Promise<unknown>> = {
  "zh-CN": () => import("./locales/zh-CN"),
  "zh-TW": () => import("./locales/zh-TW"),
  ja: () => import("./locales/ja"),
  ko: () => import("./locales/ko"),
  es: () => import("./locales/es"),
  "es-419": () => import("./locales/es-419"),
  "pt-BR": () => import("./locales/pt-br"),
  fr: () => import("./locales/fr"),
  de: () => import("./locales/de"),
  it: () => import("./locales/it"),
  ru: () => import("./locales/ru"),
  sv: () => import("./locales/sv"),
  hi: () => import("./locales/hi"),
  ar: () => import("./locales/ar"),
  he: () => import("./locales/he"),
  id: () => import("./locales/id"),
  vi: () => import("./locales/vi"),
  tr: () => import("./locales/tr"),
  pl: () => import("./locales/pl"),
  uk: () => import("./locales/uk"),
  th: () => import("./locales/th"),
  fa: () => import("./locales/fa"),
  cs: () => import("./locales/cs"),
  nl: () => import("./locales/nl"),
};

function readCatalog(module: unknown, locale: LazyLocale): MessageTree {
  const name = locale.replace("-", "");
  const catalog = (module as Record<string, unknown> | null)?.[name];
  if (catalog === undefined) {
    throw new Error(`Locale catalog "${locale}" has no "${name}" export.`);
  }
  return catalog as MessageTree;
}

export const CATALOG_RETRY_PARAM = "catalogRetry";

const CHUNK_URL_PATTERN = /\bhttps?:\/\/[^\s"'`)]+/;

let catalogRetryCount = 0;

/**
 * Chrome, Edge and Firefox < 155 cache a failed module by URL, so retry with a one-off query.
 * The URL comes from the browser's error message; Safari gives none but re-requests itself.
 */
export function catalogRetryUrl(
  error: unknown,
  previousUrl: string | null = null,
): string | null {
  const message = error instanceof Error ? error.message : String(error ?? "");
  const found = message.match(CHUNK_URL_PATTERN)?.[0] ?? previousUrl;
  if (found === null) return null;
  let url: URL;
  try {
    url = new URL(found);
  } catch {
    return null;
  }
  // A preload failure names the stylesheet, not the module that wanted it.
  if (url.pathname.endsWith(".css")) return null;
  catalogRetryCount += 1;
  url.searchParams.set(CATALOG_RETRY_PARAM, String(catalogRetryCount));
  return url.href;
}

export type CatalogImporter = (
  locale: LazyLocale,
  retryUrl: string | null,
) => Promise<unknown>;

function importCatalog(
  locale: LazyLocale,
  retryUrl: string | null,
): Promise<unknown> {
  if (retryUrl === null) return localeLoaders[locale]();
  return import(/* @vite-ignore */ retryUrl);
}

const localeLoads = new Map<Locale, Promise<void>>();
const catalogRetryUrls = new Map<Locale, string>();

export function loadLocaleMessages(
  locale: Locale,
  importer: CatalogImporter = importCatalog,
): Promise<void> | undefined {
  if (loadedMessages[locale] !== undefined) return undefined;
  const pending = localeLoads.get(locale);
  if (pending) return pending;

  if (locale === "en") return undefined;
  const retryUrl = catalogRetryUrls.get(locale) ?? null;
  const load = importer(locale, retryUrl)
    .then(
      (module) => {
        loadedMessages[locale] = readCatalog(module, locale);
        catalogRetryUrls.delete(locale);
      },
      (error: unknown) => {
        const nextUrl = catalogRetryUrl(error, retryUrl);
        if (nextUrl === null) catalogRetryUrls.delete(locale);
        else catalogRetryUrls.set(locale, nextUrl);
        throw error;
      },
    )
    .finally(() => {
      // Only if still ours: a timed-out load may already have been replaced by its retry.
      if (localeLoads.get(locale) === load) localeLoads.delete(locale);
    });
  localeLoads.set(locale, load);
  return load;
}

/** Drops a stalled load so the next pick retries; a newer attempt for this locale is never evicted. */
export function forgetLocaleLoad(locale: Locale, load?: Promise<void>): void {
  if (load !== undefined && localeLoads.get(locale) !== load) return;
  localeLoads.delete(locale);
}

const PLACEHOLDER_PATTERN = /\{([a-zA-Z0-9_]+)\}/g;

function readMessage(tree: unknown, key: string): string | undefined {
  let cursor = tree;
  for (const segment of key.split(".")) {
    if (
      cursor === null ||
      typeof cursor !== "object" ||
      !Object.prototype.hasOwnProperty.call(cursor, segment)
    ) {
      return undefined;
    }
    cursor = (cursor as Record<string, unknown>)[segment];
  }
  return typeof cursor === "string" ? cursor : undefined;
}

function interpolate(
  template: string,
  values: InterpolationValues | undefined,
): string {
  if (!values) return template;

  return template.replace(PLACEHOLDER_PATTERN, (match, name: string) => {
    if (!Object.prototype.hasOwnProperty.call(values, name)) return match;
    const value = values[name];
    return value === null || value === undefined ? "" : String(value);
  });
}

function warnMissingEnglishMessage(key: string): void {
  // Optional chain so translate() also works outside Vite (Node tooling).
  if (import.meta.env?.DEV) {
    console.warn(`[i18n] Missing English translation for key "${key}".`);
  }
}

export function translate(
  key: TranslationKey,
  values?: InterpolationValues,
  locale: Locale = getLocale(),
): string {
  const localized = readMessage(messages[locale], key);
  const fallback = localized ?? readMessage(messages.en, key);

  if (fallback === undefined) {
    warnMissingEnglishMessage(key);
    return key;
  }

  return interpolate(fallback, values);
}

export function isSupportedLocale(value: unknown): value is Locale {
  return (
    typeof value === "string" &&
    Object.prototype.hasOwnProperty.call(LOCALES, value)
  );
}