UNPKG

seyfert

Version:

The most advanced framework for discord bots

95 lines (94 loc) 2.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LangsHandler = void 0; const node_path_1 = require("node:path"); const common_1 = require("../common"); const router_1 = require("./router"); class LangsHandler extends common_1.BaseHandler { values = {}; __paths = {}; filter = (path) => path.endsWith('.js') || (!path.endsWith('.d.ts') && path.endsWith('.ts')) || path.endsWith('.json'); defaultLang; aliases = []; getLocale(locale) { return this.aliases.find(([_key, aliases]) => aliases.includes(locale))?.[0] ?? locale; } getKey(lang, message) { let value = this.values[lang]; try { for (const i of message.split('.')) { value = value[i]; } } catch { return; } if (typeof value !== 'string') { return; } return value; } get(userLocale) { const locale = this.getLocale(userLocale); return (0, router_1.LangRouter)(locale, this.defaultLang ?? locale, this.values)(); } async load(dir) { const files = await this.loadFilesK(await this.getFiles(dir)); for (const i of files) { this.parse(i); } } parse(file) { const oldLocale = file.name.split('.').slice(0, -1).join('.') || file.name; const result = this.onFile(oldLocale, file); if (!result) return; if ('path' in file) this.__paths[result.locale] = file.path; this.values[result.locale] = result.file; } set(instances) { for (const i of instances) { this.parse(i); } } async reload(lang) { if ((0, common_1.isCloudfareWorker)()) { throw new common_1.SeyfertError('RELOAD_NOT_SUPPORTED', { metadata: { detail: 'Reload in Cloudflare worker is not supported' }, }); } const path = this.__paths[lang]; if (!path) return null; delete require.cache[path]; const value = await (0, common_1.magicImport)(path).then(x => this.onFile(lang, { file: x, name: (0, node_path_1.basename)(path), path, })); if (!value) return null; return (this.values[lang] = value.file); } async reloadAll(stopIfFail = true) { for (const i in this.__paths) { try { await this.reload(i); } catch (e) { if (stopIfFail) throw e; } } } onFile(locale, { file }) { return file.default ? { file: file.default, locale, } : false; } } exports.LangsHandler = LangsHandler;