inlang

本指南将带你一步步构建一个能标记缺失翻译的工具。读完本指南,你将了解如何加载项目,以及如何使用 CRUD API 查询消息。

工具能做什么

工具通过 CRUD API 以 .inlang 格式读写翻译。插件会在边界处完成格式转换,因此你的工具可以支持任何翻译格式 (JSON、XLIFF、i18next 等) ,而无需逐一解析。

.inlang 项目在规范上是一个可移植的快照。在 Git 仓库中,它通常会被解包成一个目录;loadProjectFromDirectory() 用于加载这种便于 Git 管理的形式。

如果 project.inlang/ 目录已经存在,用 loadProjectFromDirectory() 加载即可。如果你的工具要从零生成一个新的本地化项目,先调用 newProject(),再用 project.toBlob() 保存打包后的文件。可运行的“创建-保存-重新加载”示例见快速入门。

┌─────────────────┐
│    Your Tool    │
├─────────────────┤
│    CRUD API     │  ◄── Query and modify messages
├─────────────────┤
│  .inlang file   │
├─────────────────┤
│    Plugins      │  ◄── Handle file formats
└─────────────────┘

第 1 步:加载项目

import { loadProjectFromDirectory } from "@inlang/sdk";
import fs from "node:fs";

const project = await loadProjectFromDirectory({
  path: "./project.inlang",
  fs,
});

就这么简单。项目加载后,会 (通过插件) 包含你文件中的所有翻译。外部文件只用于兼容;工具实际操作的是共享的 .inlang 数据模型。

第 2 步:检查加载错误

插件导入错误和资源文件错误可通过 project.errors.get() 获取。在采信查询结果之前,请先检查这些错误。

const errors = await project.errors.get();
if (errors.length > 0) {
  throw new AggregateError(errors, "Could not load inlang project");
}

在一次性脚本和 CLI 中,应在进程退出前关闭项目:

await project.close();

第 3 步:获取项目设置

const settings = await project.settings.get();

console.log("Base locale:", settings.baseLocale);
console.log("Locales:", settings.locales);
// 基础语言:en
// 语言列表:["en", "de", "fr"]

第 4 步:查询所有 bundle

const bundles = await project.db.selectFrom("inlang_bundle").selectAll().execute();

console.log(`Found ${bundles.length} translation keys`);

第 5 步:查找缺失的翻译

接下来,我们查找缺少某些语言区域翻译的 bundle:

async function findMissingTranslations(project) {
  const settings = await project.settings.get();
  const bundles = await project.db.selectFrom("inlang_bundle").selectAll().execute();
  const messages = await project.db.selectFrom("inlang_message").selectAll().execute();

  const missing = [];

  for (const bundle of bundles) {
    // 获取此 bundle 的所有消息
    const bundleMessages = messages.filter((m) => m.bundle_id === bundle.id);
    const localesWithTranslation = bundleMessages.map((m) => m.locale);

    // 找出缺失的语言区域
    for (const locale of settings.locales) {
      if (!localesWithTranslation.includes(locale)) {
        missing.push({
          bundle_id: bundle.id,
          locale,
        });
      }
    }
  }

  return missing;
}

第 6 步:整合在一起

下面是一个完整的 CLI 工具:

import { loadProjectFromDirectory } from "@inlang/sdk";
import fs from "node:fs";

async function main() {
  const project = await loadProjectFromDirectory({
    path: "./project.inlang",
    fs,
  });

  try {
    const errors = await project.errors.get();
    if (errors.length > 0) {
      throw new AggregateError(errors, "Could not load inlang project");
    }

    const settings = await project.settings.get();
    const bundles = await project.db.selectFrom("inlang_bundle").selectAll().execute();
    const messages = await project.db
      .selectFrom("inlang_message")
      .selectAll()
      .execute();

    const missing = [];

    for (const bundle of bundles) {
      const bundleMessages = messages.filter((m) => m.bundle_id === bundle.id);
      const localesWithTranslation = bundleMessages.map((m) => m.locale);

      for (const locale of settings.locales) {
        if (!localesWithTranslation.includes(locale)) {
          missing.push({ bundleId: bundle.id, locale });
        }
      }
    }

    if (missing.length === 0) {
      console.log("All translations complete!");
    } else {
      console.log(`Found ${missing.length} missing translations:\n`);
      for (const { bundleId, locale } of missing) {
        console.log(`  - "${bundleId}" is missing locale "${locale}"`);
      }
      process.exitCode = 1;
    }
  } finally {
    await project.close();
  }
}

main();

运行:

$ npx tsx check-translations.ts

Found 3 missing translations:

  - "greeting" is missing locale "fr"
  - "error_404" is missing locale "de"
  - "error_404" is missing locale "fr"

编写报告查询

CRUD API 由 Kysely 驱动。生成报告时,最清晰的做法通常是先查询所需的行,再在 JavaScript 中聚合:

// 查找缺少特定语言区域的 bundle
const bundles = await project.db.selectFrom("inlang_bundle").selectAll().execute();
const germanMessages = await project.db
  .selectFrom("inlang_message")
  .select("bundle_id")
  .where("locale", "=", "de")
  .execute();

const translatedBundleIds = new Set(
  germanMessages.map((message) => message.bundle_id),
);
const missingGerman = bundles.filter(
  (bundle) => translatedBundleIds.has(bundle.id) === false,
);

// 统计每个语言区域的翻译数量
const messages = await project.db.selectFrom("inlang_message").selectAll().execute();
const counts = Object.entries(
  messages.reduce<Record<string, number>>((result, message) => {
    result[message.locale] = (result[message.locale] ?? 0) + 1;
    return result;
  }, {}),
).map(([locale, count]) => ({ locale, count }));

修改翻译

工具还可以创建、更新和删除翻译:

// 添加缺失的翻译
const message = await project.db
  .insertInto("inlang_message")
  .values({
    id: crypto.randomUUID(),
    bundle_id: "greeting",
    locale: "fr",
    selectors: [],
  })
  .returning("id")
  .executeTakeFirstOrThrow();

// 添加包含文本的变体
await project.db
  .insertInto("inlang_variant")
  .values({
    id: crypto.randomUUID(),
    message_id: message.id,
    matches: [],
    pattern: [{ type: "text", value: "Bonjour!" }],
  })
  .execute();

保存更改

如果你使用的是解包格式,启用 syncInterval 后更改会自动同步。如需手动保存:

import { saveProjectToDirectory } from "@inlang/sdk";
import fs from "node:fs";

await saveProjectToDirectory({
  fs,
  project,
  path: "./project.inlang",
});

loadProjectFromDirectory() 和 saveProjectToDirectory() 都接受 node:fs。saveProjectToDirectory() 会通过导入/导出插件写入翻译资源文件。如果未配置导出插件,请改为保存规范的打包文件:

import fs from "node:fs/promises";

const blob = await project.toBlob();
await fs.writeFile("project.inlang", new Uint8Array(await blob.arrayBuffer()));

后续步骤