|
1 | 1 | import IntlMessageFormat from 'intl-messageformat' |
2 | 2 | import type { Ref } from 'vue' |
3 | | -import type { CompileError, MessageCompiler, MessageContext } from 'vue-i18n' |
| 3 | +import type { CompileError, Composer, MessageCompiler, MessageContext } from 'vue-i18n' |
4 | 4 | import { useI18n } from 'vue-i18n' |
5 | 5 |
|
| 6 | +/** |
| 7 | + * Get i18n instance, preferring Nuxt's $i18n to avoid vue-i18n's |
| 8 | + * getCurrentInstance() issues on edge runtimes with concurrent SSR requests. |
| 9 | + */ |
| 10 | +export function getSafeI18n(): Pick<Composer, 't' | 'locale'> { |
| 11 | + // Try Nuxt's $i18n first (avoids Error 27 on Cloudflare Workers) |
| 12 | + if (typeof useNuxtApp !== 'undefined') { |
| 13 | + try { |
| 14 | + const { $i18n } = useNuxtApp() |
| 15 | + if ($i18n) { |
| 16 | + return { t: $i18n.t, locale: $i18n.locale } |
| 17 | + } |
| 18 | + } catch { |
| 19 | + // Not in Nuxt context, fall through |
| 20 | + } |
| 21 | + } |
| 22 | + // Fallback to vue-i18n's useI18n |
| 23 | + return useI18n() |
| 24 | +} |
| 25 | + |
6 | 26 | export interface MessageDescriptor { |
7 | 27 | id: string |
8 | 28 | defaultMessage?: string |
@@ -174,7 +194,7 @@ export interface VIntlFormatters { |
174 | 194 | * Uses vue-i18n's useI18n() under the hood. |
175 | 195 | */ |
176 | 196 | export function useVIntl(): VIntlFormatters & { locale: Ref<string> } { |
177 | | - const { t, locale } = useI18n() |
| 197 | + const { t, locale } = getSafeI18n() |
178 | 198 |
|
179 | 199 | function formatMessage(descriptor: MessageDescriptor, values?: Record<string, unknown>): string { |
180 | 200 | const key = descriptor.id |
|
0 commit comments