ajv-ftl-i18n
Version:
Transpile Fluent (ftl) files into ajv error translations.
45 lines (42 loc) • 1.34 kB
JavaScript
// Copyright 2026 will Farrell, and ajv-ftl-i18n contributors.
// SPDX-License-Identifier: MIT
import fluentTranspile from "fluent-transpiler";
const exportDefault = `(errors) => {
if (!errors?.length) return
for (const e of errors) {
let { keyword } = e
if (keyword === 'false schema') keyword = 'falseSchema'
let source = __exports[keyword] ?? __exports['_'+keyword]
let values = {}
if (keyword === 'errorMessage') {
const [message, ...valuesPairs] = e.message.split(', ')
for (const [, key, value] of valuesPairs.join(', ').matchAll(regExpJsonPointerPairs)) {
values[key] = value.replace(regExpJsonPointerQuote, '')
}
source ??= __exports[message] ?? __exports['_'+message] ?? e.message
} else {
source ??= __exports.defaultMessage
}
if (typeof source === 'function') {
e.message = source({keyword:e.keyword, ...e.params, ...values})
} else {
e.message = source
}
}
}
const regExpJsonPointerPairs = /([a-zA-Z0-9_-]+):("[^"]*"|[^,"]+)/g
const regExpJsonPointerQuote = /(^"|"$)/g
`;
export default (ftl, options) => {
const originalError = console.error;
console.error = Function.prototype;
try {
return fluentTranspile(ftl, {
comments: false,
...options,
exportDefault,
});
} finally {
console.error = originalError;
}
};