Skip to content

Writing a format adapter

Format adapter

Registered in parla.config.ts as formats.

A FormatAdapter parses one message into the MF2 data model, all the compiler reads. A namespace’s format names it.

FormatAdapter
name Its name
parse (source) => Model.Message
parseFile Optional. (text) => { key: message | group }, for catalogs that are not JSON
import { defineConfig, type FormatAdapter } from '@parlajs/compiler';
// Every message as plain text: no params, no markup.
const text: FormatAdapter = {
name: 'text',
parse: (source) => ({ type: 'message', declarations: [], pattern: [source] }),
};
export default defineConfig({
formats: { text },
namespaces: { legal: { format: 'text', path: 'locales/{locale}/legal.json' } },
});

icu and mf2 are built in, as defaultFormats.

Without parseFile, catalogs are JSON. With it, they can be .po, .ftl, .properties or anything else; a throw is an invalid-resource diagnostic.

// Plain-text messages in `key = message` lines.
const properties: FormatAdapter = {
name: 'properties',
parse: (source) => ({ type: 'message', declarations: [], pattern: [source] }),
parseFile: (text) =>
Object.fromEntries(
text
.trim()
.split('\n')
.map((line) => {
const at = line.indexOf('=');
if (at < 0) throw new Error(`no "=" in "${line}"`);
return [line.slice(0, at).trim(), line.slice(at + 1).trim()];
}),
),
};

x18n needs a format of its own for the extension.

Give the built-in formats a YAML parser, here the yaml package:

import { defaultFormats, defineConfig } from '@parlajs/compiler';
import { parse } from 'yaml';
const { icu, mf2 } = defaultFormats;
const parseFile = (text: string): unknown => parse(text);
export default defineConfig({
formats: { icu: { ...icu, parseFile }, mf2: { ...mf2, parseFile } },
namespaces: { issues: { format: 'icu', path: 'locales/{locale}/issues.yml' } },
});
# Shown in the issue list
title: >-
Issue # {n}: {title}
count: >-
{count, plural,
one {# issue}
other {# issues}}