studiocms
Version:
Astro Native CMS for AstroDB. Built from the ground up by the Astro community.
54 lines (53 loc) • 2.03 kB
JavaScript
import { posix } from "node:path";
import { fileURLToPath } from "node:url";
import { readJson } from "@withstudiocms/internal_helpers/utils";
import { glob } from "tinyglobby";
import { translationFlagKeyOverrides } from "./overrides.js";
const translationsDir = fileURLToPath(new URL("./translations/", import.meta.url));
const availableTranslationFiles = await glob("**/*.json", { cwd: translationsDir });
const availableTranslationFileKeys = availableTranslationFiles.map((file) => posix.normalize(file).replace(/\.json$/, "")).filter(Boolean);
function checkStrings(record) {
if (typeof record !== "object" || record === null) return { count: 0, emptyStrings: 0 };
let count = 0;
let emptyStrings = 0;
for (const value of Object.values(record)) {
if (typeof value === "string") {
count++;
if (value.trim() === "") emptyStrings++;
} else if (typeof value === "object" && value !== null) {
const { count: c, emptyStrings: e } = checkStrings(value);
count += c;
emptyStrings += e;
}
}
return { count, emptyStrings };
}
const MISSING_RATIO_THRESHOLD = 0.1;
function checkThreshold(opt) {
const threshold = MISSING_RATIO_THRESHOLD;
if (opt.count === 0) return false;
return opt.emptyStrings / opt.count <= threshold;
}
const availableTranslations = (() => {
const results = {};
const translationKeys = availableTranslationFileKeys.filter((key) => key !== "en");
for (const key of translationKeys) {
const translation = readJson(`${translationsDir + key}.json`);
const result = checkStrings(translation);
if (!checkThreshold(result)) {
continue;
}
results[key] = translation;
}
return results;
})();
const availableTranslationsKeys = ["en", ...Object.keys(availableTranslations)];
const currentFlags = availableTranslationsKeys.map((key) => {
const flagKey = translationFlagKeyOverrides[key] || `lang-${key}`;
return { key, flag: flagKey };
});
export {
availableTranslationFileKeys,
availableTranslations,
currentFlags
};