inlang

L'API CRUD simplifie la création d'outils i18n. Plutôt que d'analyser et d'écrire des fichiers de traduction dans différents formats (JSON, XLIFF, YAML, etc.), vous interrogez et modifiez directement les messages. Les plugins se chargent de la conversion entre formats de fichiers, à la frontière du système.

inlang utilise Kysely pour des requêtes de base de données typées. Vous y accédez via project.db.

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

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

// project.db est une instance Kysely
const bundles = await project.db.selectFrom("inlang_bundle").selectAll().execute();

Enregistrement des modifications : les opérations CRUD mettent à jour la base de données .inlang en mémoire. Pour enregistrer un fichier .inlang compacté, appelez project.toBlob(). Pour enregistrer un répertoire project.inlang/ décompacté, saveProjectToDirectory() a besoin d'un plugin d'import/export ; sans plugin, les bundles, messages et variantes n'ont aucun chemin de fichier vers lequel être exportés.

Si le projet utilise des plugins, vérifiez await project.errors.get() après le chargement. Dans les scripts ponctuels, fermez le projet avec await project.close().

Création

Insérer un bundle

await project.db
  .insertInto("inlang_bundle")
  .values({
    id: "greeting",
    declarations: [],
  })
  .execute();

Insérer un message

const message = await project.db
  .insertInto("inlang_message")
  .values({
    id: crypto.randomUUID(),
    bundle_id: "greeting",
    locale: "en",
    selectors: [],
  })
  .returning("id")
  .executeTakeFirstOrThrow();

Insérer une variante

await project.db
  .insertInto("inlang_variant")
  .values({
    id: crypto.randomUUID(),
    message_id: message.id,
    matches: [],
    pattern: [{ type: "text", value: "Hello world!" }],
  })
  .execute();

Insertion imbriquée (bundle + messages + variantes)

import { insertBundleNested } from "@inlang/sdk";

const messageId = crypto.randomUUID();

await insertBundleNested(project.db, {
  id: "greeting",
  declarations: [],
  messages: [
    {
      id: messageId,
      bundle_id: "greeting",
      locale: "en",
      selectors: [],
      variants: [
        {
          id: crypto.randomUUID(),
          message_id: messageId,
          matches: [],
          pattern: [{ type: "text", value: "Hello!" }],
        },
      ],
    },
  ],
});

Lecture

Récupérer tous les bundles

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

Récupérer un bundle par ID

const bundle = await project.db
  .selectFrom("inlang_bundle")
  .selectAll()
  .where("id", "=", "greeting")
  .executeTakeFirst();

Récupérer les messages par paramètre régional

const messages = await project.db
  .selectFrom("inlang_message")
  .selectAll()
  .where("locale", "=", "en")
  .execute();

Récupérer les messages d'un bundle

const messages = await project.db
  .selectFrom("inlang_message")
  .selectAll()
  .where("bundle_id", "=", "greeting")
  .execute();

Obtenir les variantes d'un message

const variants = await project.db
  .selectFrom("inlang_variant")
  .selectAll()
  .where("message_id", "=", messageId)
  .execute();

Obtenir une structure imbriquée (bundle avec ses messages et ses variantes)

import { selectBundleNested } from "@inlang/sdk";

const bundle = await selectBundleNested(project.db)
  .where("inlang_bundle.id", "=", "greeting")
  .executeTakeFirst();

// Renvoie :
// {
//   id: "greeting",
//   declarations: [],
//   messages: [
//     {
//       id: "...",
//       locale: "en",
//       variants: [{ id: "...", pattern: [...] }]
//     }
//   ]
// }

Jointure entre bundles et messages

const results = await project.db
  .selectFrom("inlang_bundle")
  .leftJoin("inlang_message", "inlang_message.bundle_id", "inlang_bundle.id")
  .selectAll()
  .execute();

Trouver les traductions manquantes

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,
);

Mise à jour

Mettre à jour un bundle

await project.db
  .updateTable("inlang_bundle")
  .set({
    declarations: [{ type: "input-variable", name: "count" }],
  })
  .where("id", "=", "greeting")
  .execute();

Mettre à jour le texte d'une variante

await project.db
  .updateTable("inlang_variant")
  .set({
    pattern: [{ type: "text", value: "Updated text" }],
  })
  .where("id", "=", variantId)
  .execute();

Mise à jour de données imbriquées

import { updateBundleNested } from "@inlang/sdk";

await updateBundleNested(project.db, {
  id: "greeting",
  declarations: [],
  messages: [
    {
      id: messageId,
      locale: "en",
      selectors: [],
      variants: [
        {
          id: variantId,
          matches: [],
          pattern: [{ type: "text", value: "Updated!" }],
        },
      ],
    },
  ],
});

Supprimer

Supprimer un bundle

await project.db.deleteFrom("inlang_bundle").where("id", "=", "greeting").execute();

// Suppression en cascade : tous les messages et variantes sont supprimés

Supprimer un message

await project.db.deleteFrom("inlang_message").where("id", "=", messageId).execute();

// Suppression en cascade : toutes les variantes sont supprimées

Supprimer une variante

await project.db.deleteFrom("inlang_variant").where("id", "=", variantId).execute();

Upsert

Insère l'enregistrement s'il n'existe pas, ou le met à jour s'il existe déjà.

Upsert d'un bundle

await project.db
  .insertInto("inlang_bundle")
  .values({
    id: "greeting",
    declarations: [],
  })
  .onConflict((oc) =>
    oc.column("id").doUpdateSet({
      declarations: [],
    }),
  )
  .execute();

Upsert imbriqué

import { upsertBundleNested } from "@inlang/sdk";

await upsertBundleNested(project.db, {
  id: "greeting",
  declarations: [],
  messages: [...]
});

Étapes suivantes