inlang

I plugin gestiscono la conversione tra i formati di file esterni (JSON, i18next, XLIFF) e il modello dati interno di inlang. .inlang è il formato aperto di riferimento per la localizzazione; i file di traduzione esterni servono solo per la compatibilità. I plugin si occupano esclusivamente di importazione ed esportazione: non scrivono direttamente nel progetto .inlang.

┌─────────────────┐       ┌─────────┐       ┌──────────────────┐
│  .inlang file   │◄─────►│ Plugins │◄─────►│ Translation files│
│                 │       │         │       │  (JSON, XLIFF)   │
└─────────────────┘       └─────────┘       └──────────────────┘

Interfaccia del plugin

type InlangPlugin<ExternalSettings = unknown> = {
  key: string;
  settingsSchema?: TObject;
  toBeImportedFiles?: (args) => Promise<Array<{ path; locale; metadata? }>>;
  importFiles?: (args) => Promise<{ bundles; messages; variants }>;
  exportFiles?: (args) => Promise<Array<ExportFile>>;
  meta?: Record<string, Record<string, unknown>>;
};

Esempio minimo

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

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

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

  importFiles: async ({ files, settings }) => {
    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 ({ bundles, messages, variants, settings }) => {
    const files: 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 (!files[message.locale]) files[message.locale] = {};
      files[message.locale][message.bundleId] = text ?? "";
    }

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

Metodi

toBeImportedFiles

Individua quali file importare dal filesystem.

toBeImportedFiles: async ({ settings }) => {
  return [
    { path: "./messages/en.json", locale: "en" },
    { path: "./messages/de.json", locale: "de" },
  ];
};

Parametri:

  • settings — Impostazioni del progetto, inclusa la configurazione specifica del plugin

Restituisce: un array di descrittori di file:

  • path — Percorso del file
  • locale — Locale contenuto nel file
  • metadata — Opzionale, viene passato a importFiles

importFiles

Esegue il parsing del contenuto dei file e lo converte nel modello dati di inlang.

importFiles: async ({ files, settings }) => {
  return {
    bundles: [...],
    messages: [...],
    variants: [...],
  };
}

Parametri:

  • files — Array di file da importare:
    • locale — Il locale
    • content — Contenuto binario del file (Uint8Array)
    • toBeImportedFilesMetadata — Metadati di toBeImportedFiles
  • settings — Impostazioni del progetto

Valore restituito:

  • bundles — Array di BundleImport
  • messages — Array di MessageImport
  • variants — Array di VariantImport

exportFiles

Riconverte in file il modello dati di inlang.

exportFiles: async ({ bundles, messages, variants, settings }) => {
  return [
    {
      locale: "en",
      name: "en.json",
      content: new TextEncoder().encode(JSON.stringify(data)),
    },
  ];
};

Parametri:

  • bundles — Tutti i bundle
  • messages — Tutti i messaggi
  • variants — Tutte le varianti
  • settings — Impostazioni del progetto
  • files (opzionale) — Il contenuto attuale dei file che l'export sovrascrive: { path, locale, content, metadata? }, dove path, locale e metadata sono quelli restituiti da toBeImportedFiles (passa metadata come toBeImportedFilesMetadata per importare un file con il tuo importFiles). Vengono passati solo i file esistenti. Gli host che non lo supportano (SDK < 4) e gli export di nuovi file non passano nulla. Con un array pathPattern, una locale può avere più file esistenti.

Lascia invariate le voci non modificate. Un export dovrebbe modificare solo i byte dei messaggi cambiati, in modo che salvare un progetto non riscriva i file di traduzione in git. Se files contiene il file che un file esportato sostituisce, mantieni il testo di ogni voce il cui messaggio non è cambiato, l'ordine delle chiavi del file e la sua formattazione (indentazione, newline finale, terminatori di riga), e scrivi solo le voci modificate, aggiunte o rimosse. Confronta i messaggi in base al risultato dell'import, non in base al loro testo: un file può usare una rappresentazione diversa da quella scritta dal plugin, ad esempio una forma legacy o un escaping diverso. Se non c'è un file precedente, scrivi l'intero file.

Imposta verbatim: true su un file esportato che mantiene la formattazione del file esistente. In questo modo saveProjectToDirectory lo scrive byte per byte. Altrimenti, saveProjectToDirectory reindenta il JSON esportato come il file esistente (e usa terminatori di riga LF).

I plugin JSON possono usare keepUnchangedJsonEntries da @inlang/sdk/json-formatting. Riceve i file dell'export completo e le funzioni importFiles ed exportFiles del plugin stesso, e mantiene ogni voce del file precedente per cui il plugin scrive lo stesso valore dei nuovi dati:

import { keepUnchangedJsonEntries } from "@inlang/sdk/json-formatting";

exportFiles: async (args) =>
  keepUnchangedJsonEntries({
    exported: await exportWholeFiles(args),
    files: args.files,
    settings: args.settings,
    importFiles,
    exportFiles: exportWholeFiles,
  }),

Contrassegna come verbatim i file per cui ha riutilizzato il file precedente.

Restituisce: un array di file da scrivere:

  • locale — Il locale
  • name — Nome del file (ad es. "en.json")
  • content — Contenuto binario (Uint8Array)
  • metadata (opzionale) — Informazioni per il writer, ad es. { namespace } per un pathPattern con namespace
  • verbatim (opzionale) — true se content mantiene la formattazione del file esistente e deve essere scritto byte per byte

Schema delle impostazioni

Definisci le impostazioni del plugin con TypeBox:

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

export const PluginSettings = Type.Object({
  pathPattern: Type.String({
    pattern: ".*\\{locale\\}.*\\.json$",
    description: "Path to translation files",
    examples: ["./messages/{locale}.json"],
  }),
  sort: Type.Optional(Type.Union([Type.Literal("asc"), Type.Literal("desc")])),
});

Poi fai riferimento allo schema nel tuo plugin:

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

Gli utenti configurano il tuo plugin in settings.json:

{
  "baseLocale": "en",
  "locales": ["en", "de"],
  "modules": ["./plugins/my-plugin.js"],
  "plugin.my.json": {
    "pathPattern": "./messages/{locale}.json",
    "sort": "asc"
  }
}

Importare i tipi

BundleImport

type BundleImport = {
  id: string;
  declarations: Declaration[];
};

MessageImport

type MessageImport = {
  id?: string; // generato automaticamente se omesso
  bundleId: string;
  locale: string;
  selectors: VariableReference[];
};

VariantImport

Le varianti possono fare riferimento ai messaggi tramite ID oppure tramite bundle/locale.

Nella maggior parte delle implementazioni di importFiles(), usa messageBundleId insieme a messageLocale. In questo modo l'SDK può generare o riutilizzare gli ID dei messaggi durante l'importazione.

Usa messageId solo se il tuo plugin gestisce di proposito ID stabili per i messaggi e restituisce gli ID corrispondenti in messages.

// Per ID del messaggio
type VariantImport = {
  id?: string;
  messageId: string;
  matches: Match[];
  pattern: Pattern;
};

// Per bundle/locale
type VariantImport = {
  messageBundleId: string;
  messageLocale: string;
  matches: Match[];
  pattern: Pattern;
};

Meta

Usa meta per esporre ad altri strumenti API specifiche del plugin:

export const plugin: InlangPlugin = {
  key: "plugin.my.json",
  meta: {
    "app.inlang.ideExtension": {
      documentSelectors: [{ language: "json" }],
    },
  },
};

Prossimi passi