import type { DefaultLocale } from '../commands'; export const LangRouter = (userLocale: string, defaultLang: string, langs: Partial>) => { function createProxy( route = [] as string[], args: any[] = [], ): __InternalParseLocale & { get(locale?: string): DefaultLocale } { const noop = () => { return; }; return new Proxy(noop, { get: (_, key: string) => { if (key === 'get') { function getValue(locale?: string) { if (typeof locale === 'undefined') throw new Error('Undefined locale'); let value = langs[locale] as Record; for (const i of route) value = value[i]; return value; } return (locale?: string) => { let result; try { result = getValue(locale ?? userLocale); } catch { result = getValue(defaultLang); } const value = typeof result === 'function' ? result(...args) : result; return value; }; } return createProxy([...route, key], args); }, apply: (...[, , args]) => { return createProxy(route, args); }, }) as any; } return createProxy; }; export type __InternalParseLocale> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? (...args: Parameters) => { get(locale?: string): ReturnType } : T[K] extends string ? { get(locale?: string): T[K] } : T[K] extends unknown[] ? { get(locale?: string): T[K] } : T[K] extends Record ? __InternalParseLocale & { get(locale?: string): T[K] } : never; }; export type ParseLocales> = T; /**Idea inspiration from: FreeAoi */