test-messages.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import fs from "node:fs";
  2. import path from "node:path";
  3. type JsonValue = unknown;
  4. function readJson(filePath: string): JsonValue {
  5. return JSON.parse(fs.readFileSync(filePath, "utf8")) as JsonValue;
  6. }
  7. function loadSplitSettings(settingsDir: string): Record<string, JsonValue> {
  8. const top: Record<string, JsonValue> = {};
  9. for (const entry of fs.readdirSync(settingsDir, { withFileTypes: true })) {
  10. if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
  11. const name = entry.name.replace(/\.json$/, "");
  12. const value = readJson(path.join(settingsDir, entry.name));
  13. if (name === "strings" && value && typeof value === "object") {
  14. Object.assign(top, value);
  15. continue;
  16. }
  17. top[name] = value;
  18. }
  19. const providersDir = path.join(settingsDir, "providers");
  20. const providers: Record<string, JsonValue> = {};
  21. if (fs.existsSync(providersDir)) {
  22. for (const entry of fs.readdirSync(providersDir, { withFileTypes: true })) {
  23. if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
  24. const name = entry.name.replace(/\.json$/, "");
  25. const value = readJson(path.join(providersDir, entry.name));
  26. if (name === "strings" && value && typeof value === "object") {
  27. Object.assign(providers, value);
  28. continue;
  29. }
  30. providers[name] = value;
  31. }
  32. const formDir = path.join(providersDir, "form");
  33. const form: Record<string, JsonValue> = {};
  34. if (fs.existsSync(formDir)) {
  35. for (const entry of fs.readdirSync(formDir, { withFileTypes: true })) {
  36. if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
  37. const name = entry.name.replace(/\.json$/, "");
  38. const value = readJson(path.join(formDir, entry.name));
  39. if (name === "strings" && value && typeof value === "object") {
  40. Object.assign(form, value);
  41. continue;
  42. }
  43. form[name] = value;
  44. }
  45. }
  46. providers.form = form;
  47. }
  48. top.providers = providers;
  49. return top;
  50. }
  51. function loadSettingsMessages(base: string): JsonValue {
  52. const legacy = path.join(base, "settings.json");
  53. if (fs.existsSync(legacy)) return readJson(legacy);
  54. const splitDir = path.join(base, "settings");
  55. return loadSplitSettings(splitDir);
  56. }
  57. export function loadMessages(locale: string = "en") {
  58. const base = path.join(process.cwd(), "messages", locale);
  59. const read = (name: string) => readJson(path.join(base, name));
  60. return {
  61. common: read("common.json"),
  62. errors: read("errors.json"),
  63. ui: read("ui.json"),
  64. forms: read("forms.json"),
  65. settings: loadSettingsMessages(base),
  66. };
  67. }