Skip to content

Commit

Permalink
fix: extractDefineI18nRouteConfig change to extractLocaleRoutes
Browse files Browse the repository at this point in the history
  • Loading branch information
s00d committed Oct 15, 2024
1 parent a7a8bbd commit 3047dd3
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 44 deletions.
4 changes: 3 additions & 1 deletion playground/pages/subpage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,11 @@ import { useNuxtApp } from '#imports'
const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t, $tc, $defineI18nRoute } = useNuxtApp()
const locale_en = { greeting: 'Hello', farewell: 'Goodbye' }
$defineI18nRoute({
locales: {
en: { greeting: 'Hello', farewell: 'Goodbye' },
en: locale_en,
ru: { greeting: 'Привет', farewell: 'До свидания' },
de: { greeting: 'Hallo', farewell: 'Auf Wiedersehen' },
},
Expand Down
8 changes: 4 additions & 4 deletions src/page-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { readFileSync } from 'node:fs'
import type { NuxtPage } from '@nuxt/schema'
import type { GlobalLocaleRoutes, Locale } from './types'
import {
extractDefineI18nRouteConfig,
normalizePath,
isLocaleDefault,
isPageRedirectOnly,
Expand All @@ -12,6 +11,7 @@ import {
shouldAddLocalePrefix,
buildFullPath,
removeLeadingSlash,
extractLocaleRoutes,
} from './utils'

// Класс PageManager
Expand Down Expand Up @@ -83,11 +83,11 @@ export class PageManager {
if (page.file) {
const filePath = path.resolve(rootDir, page.file)
const fileContent = readFileSync(filePath, 'utf-8')
const i18nRouteConfig = extractDefineI18nRouteConfig(fileContent, filePath)
const localeRoutes = extractLocaleRoutes(fileContent, filePath)

if (i18nRouteConfig?.localeRoutes) {
if (localeRoutes) {
const normalizedFullPath = normalizePath(path.join(parentPath, page.path))
localizedPaths[normalizedFullPath] = i18nRouteConfig.localeRoutes
localizedPaths[normalizedFullPath] = localeRoutes
}
}
}
Expand Down
64 changes: 25 additions & 39 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,40 @@
import path from 'node:path'
import type { NuxtPage } from '@nuxt/schema'
import type { DefineI18nRouteConfig, Locale } from './types'
import type { Locale, LocaleCode } from './types'

function normalizeLocales(localesArray: string[]): Record<string, object> {
const localesObject: Record<string, object> = {}
for (const locale of localesArray) {
localesObject[locale] = {} // Присваиваем пустой объект как значение для каждого ключа
}
return localesObject
}
export function extractLocaleRoutes(content: string, filePath: string): Record<string, string> | null {
// Ищем вызов defineI18nRoute (с долларом или без)
const defineMatch = content.match(/\$?\bdefineI18nRoute\s*\(\s*\{[\s\S]*?\}\s*\)/)
if (defineMatch) {
// Ищем блок localeRoutes внутри вызова defineI18nRoute
const localeRoutesMatch = defineMatch[0].match(/localeRoutes:\s*(\{[\s\S]*?\})/)

export function extractDefineI18nRouteConfig(content: string, filePath: string): DefineI18nRouteConfig | null {
const match = content.match(/^[ \t]*\$defineI18nRoute\((\{[\s\S]*?\})\)/m)
if (match && match[1]) {
try {
const parsedObject = Function('"use strict";return (' + match[1] + ')')()

// Добавляем нормализацию массивов в объекты
if (parsedObject.locales && Array.isArray(parsedObject.locales)) {
parsedObject.locales = normalizeLocales(parsedObject.locales)
}
if (localeRoutesMatch && localeRoutesMatch[1]) {
try {
// Парсим найденный блок localeRoutes
const parsedLocaleRoutes = Function('"use strict";return (' + localeRoutesMatch[1] + ')')()

if (validateDefineI18nRouteConfig(parsedObject)) {
return parsedObject
if (typeof parsedLocaleRoutes === 'object' && parsedLocaleRoutes !== null) {
if (validateDefineI18nRouteConfig(parsedLocaleRoutes)) {
return parsedLocaleRoutes
}
}
else {
console.error('localeRoutes found but it is not a valid object in file:', filePath)
}
}
else {
console.error('Invalid defineI18nRoute configuration format:', parsedObject, 'in file: ', filePath)
catch (error) {
console.error('Failed to parse localeRoutes:', error, 'in file:', filePath)
}
}
catch (error) {
console.error('Failed to parse defineI18nRoute configuration:', error, 'in file: ', filePath)
}
}
return null
}

export function validateDefineI18nRouteConfig(obj: DefineI18nRouteConfig): boolean {
if (typeof obj !== 'object' || obj === null) return false
if (obj.locales) {
if (typeof obj.locales !== 'object') return false
for (const localeKey in obj.locales) {
const translations = obj.locales[localeKey]
if (typeof translations !== 'object' || translations === null) return false
}
}
if (obj.localeRoutes) {
if (typeof obj.localeRoutes !== 'object') return false
for (const routeKey in obj.localeRoutes) {
if (typeof obj.localeRoutes[routeKey] !== 'string') return false
}
export function validateDefineI18nRouteConfig(obj: Record<LocaleCode, Record<string, string>>): boolean {
if (typeof obj !== 'object') return false
for (const routeKey in obj.localeRoutes) {
if (typeof obj.localeRoutes[routeKey] !== 'string') return false
}
return true
}
Expand Down

0 comments on commit 3047dd3

Please sign in to comment.