next-intl
Version:
Internationalization (i18n) for Next.js
2 lines (1 loc) • 1.51 kB
JavaScript
import e from"fs";import s from"fs/promises";import t from"path";class a{onChangeCallbacks=new Set;constructor(e){this.messagesDir=e.messagesDir,this.sourceLocale=e.sourceLocale,this.extension=e.extension,this.locales=e.locales}async getTargetLocales(){return this.targetLocales||("infer"===this.locales?this.targetLocales=await this.readTargetLocales():this.targetLocales=this.locales.filter((e=>e!==this.sourceLocale))),this.targetLocales}async readTargetLocales(){try{return(await s.readdir(this.messagesDir)).filter((e=>e.endsWith(this.extension))).map((e=>t.basename(e,this.extension))).filter((e=>e!==this.sourceLocale))}catch{return[]}}subscribeLocalesChange(e){this.onChangeCallbacks.add(e),"infer"!==this.locales||this.watcher||this.startWatcher()}unsubscribeLocalesChange(e){this.onChangeCallbacks.delete(e),0===this.onChangeCallbacks.size&&this.stopWatcher()}async startWatcher(){this.watcher||(await s.mkdir(this.messagesDir,{recursive:!0}),this.watcher=e.watch(this.messagesDir,{persistent:!1,recursive:!1},((e,s)=>{null!=s&&s.endsWith(this.extension)&&!s.includes(t.sep)&&this.onChange()})))}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=void 0)}async onChange(){const e=new Set(this.targetLocales||[]);this.targetLocales=await this.readTargetLocales();const s=new Set(this.targetLocales),t=this.targetLocales.filter((s=>!e.has(s))),a=Array.from(e).filter((e=>!s.has(e)));if(t.length>0||a.length>0)for(const e of this.onChangeCallbacks)e({added:t,removed:a})}}export{a as default};