inlang

このガイドでは、プラグインをゼロから作成する手順を説明します。ガイドを終える頃には、独自の JSON 形式をインポート・エクスポートできる、実際に動作するプラグインが完成しています。

プラグインの役割

プラグインは、外部のファイル形式とinlangの内部データモデルを相互に変換します:

Translation files  ──►  importFiles()  ──►  Bundles/Messages/Variants
                                                     │
                                                     ▼
                                               .inlang database
                                                     │
                                                     ▼
Translation files  ◄──  exportFiles()  ◄──  Bundles/Messages/Variants

loadProjectFromDirectory() でプロジェクトを読み込むと、SDK は設定済みのインポート/エクスポートプラグインの toBeImportedFiles() を呼び出し、次に importFiles() を呼び出します。saveProjectToDirectory() でプロジェクトを保存すると、SDK は exportFiles() を呼び出します。

プラグインの読み込みエラーやリソースファイルのエラーは、読み込んだプロジェクトの await project.errors.get() で取得できます。

ステップ 1: プラグインファイルを作成する

プラグイン用のファイルを新規作成します。

// my-plugin.ts
import type { InlangPlugin } from "@inlang/sdk";

export const plugin: InlangPlugin = {
  key: "plugin.my.json",
};

key はプラグインを一意に識別するための値です。plugin.company.format のような名前空間付きの形式を使ってください。

ステップ 2: インポートするファイルを定義する

toBeImportedFiles を実装し、プラグインが扱うファイルを inlang に指定します。

export const plugin: InlangPlugin = {
  key: "plugin.my.json",

  toBeImportedFiles: async ({ settings }) => {
    // ロケールごとに1つのファイルを返す
    return settings.locales.map((locale) => ({
      path: `./messages/${locale}.json`,
      locale,
    }));
  },
};

この設定は inlang に「プロジェクトの各ロケールについて、./messages/{locale}.json に JSON ファイルがある」ことを伝えます。

ステップ 3: ファイルをデータモデルにパースする

importFiles を実装し、使用するファイル形式をパースします。

export const plugin: InlangPlugin = {
  key: "plugin.my.json",

  toBeImportedFiles: async ({ settings }) => {
    return settings.locales.map((locale) => ({
      path: `./messages/${locale}.json`,
      locale,
    }));
  },

  importFiles: async ({ files }) => {
    const bundles = [];
    const messages = [];
    const variants = [];

    for (const file of files) {
      // JSONファイルをパースする
      const json = JSON.parse(new TextDecoder().decode(file.content));

      // 各キーと値のペアをデータモデルに変換する
      for (const [key, value] of Object.entries(json)) {
        // 翻訳キーごとにバンドルを1つ作成
        bundles.push({
          id: key,
          declarations: [],
        });

        // ロケールごとにメッセージを1つ作成
        messages.push({
          bundleId: key,
          locale: file.locale,
          selectors: [],
        });

        // 実際のテキストを持つバリアントを1つ作成。SDKはインポート時にメッセージIDを
        // 生成することがあるため、プラグインは通常バンドル + ロケールでバリアントを紐付ける。
        variants.push({
          messageBundleId: key,
          messageLocale: file.locale,
          matches: [],
          pattern: [{ type: "text", value: value as string }],
        });
      }
    }

    return { bundles, messages, variants };
  },
};

importFiles() から返すバリアントには、messageBundleId と messageLocale を組み合わせて使用します。messageId は、プラグインが安定したメッセージ ID も返す場合にのみ使用してください。直接 CRUD 操作を行う例で messageId を使っているのは、既存のデータベース行を操作するためです。

データモデルを理解する

  • バンドル — 翻訳キー (例: "greeting") 。全ロケールのバージョンをまとめたもの。
  • メッセージ — バンドルの特定ロケール版。バンドルとロケールを結び付けます。
  • バリアント — 実際のテキスト。ほとんどのメッセージはバリアントが1つですが、複数形では複数になります。

シンプルな { "greeting": "Hello" } の場合:

Bundle: id="greeting"
└── Message: bundleId="greeting", locale="en"
    └── Variant: pattern=[{ type: "text", value: "Hello" }]

ステップ4: ファイルにエクスポートする

exportFiles を実装して、変更をファイルに書き戻します。

exportFiles: async ({ bundles, messages, variants }) => {
  // メッセージをロケールごとにグループ化
  const filesByLocale: Record<string, Record<string, string>> = {};

  for (const message of messages) {
    // このメッセージのバリアントを検索
    const variant = variants.find((v) => v.messageId === message.id);

    // パターンからテキストを抽出
    const text = variant?.pattern
      .filter((p) => p.type === "text")
      .map((p) => p.value)
      .join("") ?? "";

    // 該当ロケールのファイルに追加
    if (!filesByLocale[message.locale]) {
      filesByLocale[message.locale] = {};
    }
    filesByLocale[message.locale][message.bundleId] = text;
  }

  // エクスポート形式に変換
  return Object.entries(filesByLocale).map(([locale, content]) => ({
    locale,
    name: `${locale}.json`,
    content: new TextEncoder().encode(JSON.stringify(content, null, 2)),
  }));
},

exportFiles() は { locale, name, content } オブジェクトを返す必要があります。プラグイン設定で pathPattern が定義されていない場合、name がフォールバックのファイル名として使われます。プロジェクト設定に settings[plugin.key].pathPattern が含まれている場合、saveProjectToDirectory() は代わりにそのパスへ書き込みます。

相対パスの pathPattern は、project.inlang/ を含むディレクトリを基準に解決されます。

exportFiles() は files も受け取ります。これは toBeImportedFiles() が列挙したファイルのうち、実際に存在するものの現在の内容です。これを使って変更のないエントリのテキストをそのまま残せば、エクスポート時に git 上の翻訳ファイルで編集したメッセージ以外の箇所まで書き換わるのを防げます。詳しくは変更のないエントリを保持するを参照してください。

ステップ 5: 設定を追加する (任意)

設定スキーマを定義すると、ユーザーがプラグインを設定できるようになります。

import { Type } from "@sinclair/typebox";

const PluginSettings = Type.Object({
  pathPattern: Type.String({
    description: "Path pattern for translation files",
    examples: ["./messages/{locale}.json"],
  }),
});

export const plugin: InlangPlugin<{
  "plugin.my.json": typeof PluginSettings;
}> = {
  key: "plugin.my.json",
  settingsSchema: PluginSettings,

  toBeImportedFiles: async ({ settings }) => {
    const pattern =
      settings["plugin.my.json"]?.pathPattern ?? "./messages/{locale}.json";

    return settings.locales.map((locale) => ({
      path: pattern.replace("{locale}", locale),
      locale,
    }));
  },

  // ... プラグインの残りの実装
};

ユーザーは settings.json で次のように設定します:

{
  "baseLocale": "en",
  "locales": ["en", "de", "fr"],
  "modules": ["./my-plugin.js"],
  "plugin.my.json": {
    "pathPattern": "./i18n/{locale}.json"
  }
}

完全なコード例

プラグインの全体は次のとおりです。

import type { InlangPlugin } from "@inlang/sdk";
import { Type } from "@sinclair/typebox";

const PluginSettings = Type.Object({
  pathPattern: Type.String({
    description: "Path pattern for translation files",
    examples: ["./messages/{locale}.json"],
  }),
});

export const plugin: InlangPlugin<{
  "plugin.my.json": typeof PluginSettings;
}> = {
  key: "plugin.my.json",
  settingsSchema: PluginSettings,

  toBeImportedFiles: async ({ settings }) => {
    const pattern =
      settings["plugin.my.json"]?.pathPattern ?? "./messages/{locale}.json";

    return settings.locales.map((locale) => ({
      path: pattern.replace("{locale}", locale),
      locale,
    }));
  },

  importFiles: async ({ files }) => {
    const bundles = [];
    const messages = [];
    const variants = [];

    for (const file of files) {
      const json = JSON.parse(new TextDecoder().decode(file.content));

      for (const [key, value] of Object.entries(json)) {
        bundles.push({ id: key, declarations: [] });
        messages.push({
          bundleId: key,
          locale: file.locale,
          selectors: [],
        });
        variants.push({
          messageBundleId: key,
          messageLocale: file.locale,
          matches: [],
          pattern: [{ type: "text", value: value as string }],
        });
      }
    }

    return { bundles, messages, variants };
  },

  exportFiles: async ({ messages, variants }) => {
    const filesByLocale: Record<string, Record<string, string>> = {};

    for (const message of messages) {
      const variant = variants.find((v) => v.messageId === message.id);
      const text =
        variant?.pattern
          .filter((p) => p.type === "text")
          .map((p) => p.value)
          .join("") ?? "";

      if (!filesByLocale[message.locale]) {
        filesByLocale[message.locale] = {};
      }
      filesByLocale[message.locale][message.bundleId] = text;
    }

    return Object.entries(filesByLocale).map(([locale, content]) => ({
      locale,
      name: `${locale}.json`,
      content: new TextEncoder().encode(JSON.stringify(content, null, 2)),
    }));
  },
};

次のステップ

  • 変数の処理:{name} 構文をパースして式パターンに変換する
  • 複数形の処理:一致条件を持つ複数のバリアントを作成する
  • Message Shapes — パターン、一致条件、宣言の具体的な構造
  • Plugin API — 型の完全なリファレンス
  • Data Model — バンドル、メッセージ、バリアントについて理解する
  • Architecture — プラグインが全体のどこに位置づけられるかを確認する