UNPKG

@nuxtjs/i18n

Version:

Internationalization for Nuxt

48 lines (47 loc) 1.68 kB
import { getRequestURL } from "h3"; import { setupVueI18nOptions } from "../shared/vue-i18n.js"; import { useRuntimeI18n } from "../shared/utils.js"; import { createLocaleConfigs, getDefaultLocaleForDomain } from "../shared/locales.js"; export function useI18nContext(event) { if (event.context.nuxtI18n == null) { throw new Error("Nuxt I18n server context has not been set up yet."); } return event.context.nuxtI18n; } export function tryUseI18nContext(event) { return event.context.nuxtI18n; } const getHost = (event) => getRequestURL(event, { xForwardedHost: true }).host; export async function initializeI18nContext(event) { const runtimeI18n = useRuntimeI18n(void 0, event); const defaultLocale = runtimeI18n.defaultLocale || ""; const options = await setupVueI18nOptions(getDefaultLocaleForDomain(getHost(event)) || defaultLocale); const localeConfigs = createLocaleConfigs(options.fallbackLocale); const ctx = createI18nContext(); ctx.vueI18nOptions = options; ctx.localeConfigs = localeConfigs; event.context.nuxtI18n = ctx; return ctx; } export const fetchMessages = async (locale) => { const headers = new Headers({ "x-nuxt-i18n": "internal" }); if (import.meta.dev) { headers.set("Cache-Control", "no-cache"); } return await $fetch(`${__I18N_SERVER_ROUTE__}/${__I18N_LOCALE_HASHES__[locale]}/${locale}/messages.json`, { headers }); }; export function createI18nContext() { return { messages: {}, slp: {}, localeConfigs: {}, trackMap: {}, vueI18nOptions: void 0, trackKey(key, locale) { this.trackMap[locale] ??= /* @__PURE__ */ new Set(); this.trackMap[locale].add(key); } }; }