'use server' import { fallbackLocale, type loc, locales } from '@/config/locales' import { getCurrentLocale } from '@/locales/server' import { getDirectories } from '@/lib/server' type Params = { [index: string]: number | string } interface DoParamsProps { key: string; params?: Params | null | undefined; } const doParams = async ({ key, params }: DoParamsProps): Promise => { if (key.trim().length === 0 || Object?.keys({ params }).length === 0) return key for (let val in params) {key = key.replace(`{${val}}`, params[val] as string)} return key } export const __ct = async ({ key, params }: { key: string | null | undefined, params?: {} }, locale?: loc) => { key = (key ?? '').trim() if (key.length === 0) return key locale ??= getCurrentLocale() if (!locales.includes(locale)) { locale = fallbackLocale } const keys = key.split('.') const scopes = await getDirectories(`${process.cwd()}/locales/custom`) if (keys.length < 2 && !scopes.includes(keys[0])) return key const scope = keys.shift() let data: any = await import(`@/locales/custom/${scope}/${locale}`).then(({ default: data }) => data).catch(() => false) if (data === false) return key let c: number = keys.length if (c === 1) { const _ = data.hasOwnProperty(keys[0]) && typeof data[keys[0]] === 'string' ? data[keys[0]] : key return await doParams({ key: _, params }) } for (let i in keys) { if (data.hasOwnProperty(keys[i])) { data = data[keys[i]] c-- } } return await doParams({ key: c === 0 ? data : key, params }) } export const _ctBatch = async (keys: { [index: string]: string | [string, Params] }, scope?: string | null) => { for (const k in keys) { let key: string = scope ? scope + '.' : '' let params: Params | undefined = undefined if (Array.isArray(keys[k])) { key += keys[k][0] params = keys[k][1] as Params } else { key += keys[k] } keys[k] = await __ct({ key, params }) } return keys }