Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use generated tsconfig and virtual file augmentations #3112

Merged
Merged
76 changes: 76 additions & 0 deletions internals.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
declare module '#build/i18n.options.mjs' {
import type { DeepRequired } from 'ts-essentials'
/**
* stub type definition for @nuxtjs/i18n internally
*/

type VueI18nConfig = import('./dist/types').VueI18nConfig
type NuxtI18nOptions = import('./dist/types').NuxtI18nOptions
type LocaleObject = import('./dist/types').LocaleObject

type LocaleLoader = {
key: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
load: () => Promise<any>
cache: boolean
}

export const localeLoaders: Record<string, LocaleLoader[]>

export const vueI18nConfigs: VueI18nConfig[]

export const localeCodes: string[]
export const nuxtI18nOptions: DeepRequired<NuxtI18nOptions<Context>>
export const normalizedLocales: LocaleObject[]
export const isSSG = false
export const parallelPlugin: boolean

export const NUXT_I18N_MODULE_ID = ''
export const DEFAULT_DYNAMIC_PARAMS_KEY: string
export const DEFAULT_COOKIE_KEY: string
export const SWITCH_LOCALE_PATH_LINK_IDENTIFIER: string
}

declare module '#internal/i18n/options.mjs' {
import type { DeepRequired } from 'ts-essentials'

type VueI18nConfig = import('./dist/types').VueI18nConfig
type NuxtI18nOptions = import('./dist/types').NuxtI18nOptions
type LocaleObject = import('./dist/types').LocaleObject

/**
* stub type definition for @nuxtjs/i18n internally
*/

type LocaleLoader = {
key: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
load: () => Promise<any>
cache: boolean
}

export const localeLoaders: Record<string, LocaleLoader[]>

export const vueI18nConfigs: VueI18nConfig[]

export const localeCodes: string[]
export const nuxtI18nOptions: DeepRequired<NuxtI18nOptions<Context>>
export const normalizedLocales: LocaleObject[]
export const isSSG = false
export const parallelPlugin: boolean

export const NUXT_I18N_MODULE_ID = ''
export const DEFAULT_DYNAMIC_PARAMS_KEY: string
export const DEFAULT_COOKIE_KEY: string
export const SWITCH_LOCALE_PATH_LINK_IDENTIFIER: string
}

declare module '#internal/i18n/locale.detector.mjs' {
export const localeDetector: import('./dist/runtime/composables/server').LocaleDetector
}

declare module 'virtual:nuxt-i18n-logger' {
import type { ConsolaInstance } from 'consola'

export function createLogger(label: string): ConsolaInstance
}
12 changes: 8 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@
"require": "./dist/module.cjs",
"types": "./dist/types.d.ts"
},
"./internals": {
"types": "./internals.d.ts"
},
"./package.json": "./package.json"
},
"imports": {
Expand All @@ -47,17 +50,18 @@
"types": "./dist/types.d.ts",
"type": "module",
"files": [
"dist"
"dist",
"internals.d.ts"
],
"scripts": {
"prepare": "git config --local core.hooksPath .githooks",
"build": "nuxi build-module .",
"stub": "nuxi build-module --stub .",
"build": "nuxt-module-build build .",
BobbieGoede marked this conversation as resolved.
Show resolved Hide resolved
"stub": "nuxt-module-build build --stub .",
"prepack": "pnpm build",
"release": "bumpp --commit \"release: v%s\" --push --tag",
"changelog": "gh-changelogen --repo=nuxt-community/i18n-module",
"dev": "pnpm dev:prepare && pnpm build --sourcemap && nuxi dev playground",
"dev:prepare": "nuxi prepare",
"dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
"dev:build": "nuxi build playground",
"dev:generate": "nuxi generate playground",
"dev:preview": "nuxi preview playground",
Expand Down
5 changes: 0 additions & 5 deletions src/logger.d.ts

This file was deleted.

15 changes: 10 additions & 5 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
addTemplate,
addTypeTemplate,
addImports,
useLogger
useLogger,
createResolver
} from '@nuxt/kit'
import { resolve, relative } from 'pathe'
import { defu } from 'defu'
Expand All @@ -33,7 +34,7 @@ import {
getLocaleFiles,
filterLocales
} from './utils'
import { distDir, runtimeDir } from './dirs'
import { runtimeDir } from './dirs'
import { applyLayerOptions, checkLayerOptions, resolveLayerVueI18nConfigInfo } from './layers'
import { generateTemplateNuxtI18nOptions } from './template'
import { i18nVirtualLoggerPlugin, RESOLVED_VIRTUAL_NUXT_I18N_LOGGER, VIRTUAL_NUXT_I18N_LOGGER } from './virtual-logger'
Expand All @@ -59,6 +60,10 @@ export default defineNuxtModule<NuxtI18nOptions>({
async setup(i18nOptions, nuxt) {
const logger = useLogger(NUXT_I18N_MODULE_ID)

nuxt.hook('prepare:types', ({ references }) => {
references.push({ types: `${NUXT_I18N_MODULE_ID}/internals` })
})

const options = i18nOptions as Required<NuxtI18nOptions>
applyOptionOverrides(options, nuxt)
debug('options', options)
Expand Down Expand Up @@ -180,8 +185,9 @@ export default defineNuxtModule<NuxtI18nOptions>({
addPlugin(resolve(runtimeDir, 'plugins/i18n'))
addPlugin(resolve(runtimeDir, 'plugins/switch-locale-path-ssr'))

const resolver = createResolver(import.meta.url)
// for composables
nuxt.options.alias['#i18n'] = resolve(distDir, 'runtime/composables/index.js')
nuxt.options.alias['#i18n'] = resolver.resolve('./runtime/composables/index')
BobbieGoede marked this conversation as resolved.
Show resolved Hide resolved
nuxt.options.build.transpile.push('#i18n')
nuxt.options.build.transpile.push(VIRTUAL_NUXT_I18N_LOGGER)

Expand All @@ -206,7 +212,6 @@ export default defineNuxtModule<NuxtI18nOptions>({
})
}

// @ts-expect-error type error
nuxt.options.runtimeConfig.public.i18n.locales = simplifyLocaleOptions(nuxt, defu({}, options))

addTemplate({
Expand Down Expand Up @@ -448,7 +453,7 @@ declare module '@nuxt/schema' {
['i18n']?: Partial<UserNuxtI18nOptions>
}
interface NuxtOptions {
['i18n']?: UserNuxtI18nOptions
['i18n']: UserNuxtI18nOptions
}
interface NuxtHooks extends ModuleHooks {}
interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
Expand Down
32 changes: 0 additions & 32 deletions src/options.d.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/runtime/composables/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { getLocale, getLocales, getComposer } from '../compatibility'
import type { Ref } from 'vue'
import type { Locale } from 'vue-i18n'
import type { RouteLocation, RouteLocationNormalizedLoaded, RouteLocationRaw, Router } from 'vue-router'
import type { I18nHeadMetaInfo, I18nHeadOptions, SeoAttributesOptions } from '#build/i18n.options.mjs'
import type { I18nHeadMetaInfo, I18nHeadOptions, SeoAttributesOptions } from '../../types'
import type { HeadParam } from '../utils'

export * from 'vue-i18n'
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/composables/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export type LocaleConfig = {
* @remarks
* That is set by `fallbackLocale` option that is loaded with `vueI18n` option (i18n.config). If these do not resolve the fallback locale, use as default `false
*/
fallbackLocale: FallbackLocale
fallbackLocale?: FallbackLocale
}

/**
Expand Down
13 changes: 7 additions & 6 deletions src/runtime/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { initCommonComposableOptions, type CommonComposableOptions } from './uti
import { createLogger } from 'virtual:nuxt-i18n-logger'

import type { Locale } from 'vue-i18n'
import type { DetectBrowserLanguageOptions, LocaleObject } from '#build/i18n.options.mjs'
import type { DetectBrowserLanguageOptions, LocaleObject } from '../types'
import type { RouteLocationNormalized, RouteLocationNormalizedLoaded } from 'vue-router'
import type { CookieRef, NuxtApp } from 'nuxt/app'
import type { ModulePublicRuntimeConfig } from '../module'
Expand Down Expand Up @@ -350,7 +350,7 @@ export function getDomainFromLocale(localeCode: Locale): string | undefined {
const nuxtApp = useNuxtApp()
const host = getHost()
// lookup the `differentDomain` origin associated with given locale.
const config = runtimeConfig.public.i18n
const config = runtimeConfig.public.i18n as ModulePublicRuntimeConfig['i18n']
const lang = normalizedLocales.find(locale => locale.code === localeCode)
const domain = config?.domainLocales?.[localeCode]?.domain || lang?.domain || lang?.domains?.find(v => v === host)

Expand All @@ -374,7 +374,7 @@ export function getDomainFromLocale(localeCode: Locale): string | undefined {
}

export const runtimeDetectBrowserLanguage = (
opts: ModulePublicRuntimeConfig['i18n'] = useRuntimeConfig().public.i18n
opts: ModulePublicRuntimeConfig['i18n'] = useRuntimeConfig().public.i18n as ModulePublicRuntimeConfig['i18n']
) => {
if (opts?.detectBrowserLanguage === false) return false

Expand All @@ -385,8 +385,8 @@ export const runtimeDetectBrowserLanguage = (
* Removes default routes depending on domain
*/
export function setupMultiDomainLocales(nuxtContext: NuxtApp, defaultLocaleDomain: string) {
const { multiDomainLocales, strategy, routesNameSeparator, defaultLocaleRouteNameSuffix } =
nuxtContext.$config.public.i18n
const { multiDomainLocales, strategy, routesNameSeparator, defaultLocaleRouteNameSuffix } = nuxtContext.$config.public
.i18n as ModulePublicRuntimeConfig['i18n']

// feature disabled
if (!multiDomainLocales) return
Expand Down Expand Up @@ -419,7 +419,8 @@ export function setupMultiDomainLocales(nuxtContext: NuxtApp, defaultLocaleDomai
* Returns default locale for the current domain, returns `defaultLocale` by default
*/
export function getDefaultLocaleForDomain(nuxtContext: NuxtApp) {
const { locales, defaultLocale, multiDomainLocales } = nuxtContext.$config.public.i18n
const { locales, defaultLocale, multiDomainLocales } = nuxtContext.$config.public
.i18n as ModulePublicRuntimeConfig['i18n']

let defaultLocaleDomain: string = defaultLocale || ''

Expand Down
10 changes: 7 additions & 3 deletions src/runtime/plugins/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import {
isSSG,
localeLoaders,
parallelPlugin,
normalizedLocales,
type LocaleObject
normalizedLocales
} from '#build/i18n.options.mjs'
import { loadVueI18nOptions, loadInitialMessages, loadLocale } from '../messages'
import { loadAndSetLocale, detectLocale, detectRedirect, navigate, injectNuxtHelpers, extendBaseUrl } from '../utils'
Expand All @@ -30,6 +29,8 @@ import { createLogger } from 'virtual:nuxt-i18n-logger'
import type { NuxtI18nPluginInjections } from '../injections'
import type { Locale, I18nOptions } from 'vue-i18n'
import type { NuxtApp } from '#app'
import type { LocaleObject } from '../../types'
import type { ModulePublicRuntimeConfig } from '../../module'

// from https://github.com/nuxt/nuxt/blob/2466af53b0331cdb8b17c2c3b08675c5985deaf3/packages/nuxt/src/core/templates.ts#L152
type Decorate<T extends Record<string, unknown>> = { [K in keyof T as K extends string ? `$${K}` : never]: T[K] }
Expand Down Expand Up @@ -57,7 +58,10 @@ export default defineNuxtPlugin<NuxtI18nPluginInjections>({
setupMultiDomainLocales(nuxtContext, defaultLocaleDomain)

// Fresh copy per request to prevent reusing mutated options
const runtimeI18n = { ...nuxtContext.$config.public.i18n, defaultLocale: defaultLocaleDomain }
const runtimeI18n = {
...(nuxtContext.$config.public.i18n as ModulePublicRuntimeConfig['i18n']),
defaultLocale: defaultLocaleDomain
}
// @ts-expect-error type incompatible
runtimeI18n.baseUrl = extendBaseUrl()

Expand Down
8 changes: 4 additions & 4 deletions src/runtime/routing/compatibles/head.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { getRouteBaseName, localeRoute, switchLocalePath } from './routing'
import { getComposer, getLocale, getLocales } from '../../compatibility'

import type { I18n } from 'vue-i18n'
import type { I18nHeadMetaInfo, MetaAttrs, LocaleObject, I18nHeadOptions } from '#build/i18n.options.mjs'
import type { I18nHeadMetaInfo, MetaAttrs, LocaleObject, I18nHeadOptions } from '../../../types'
import type { CommonComposableOptions } from '../../utils'

/**
Expand Down Expand Up @@ -73,7 +73,7 @@ export function localeHead(

function getBaseUrl() {
const nuxtApp = useNuxtApp()
const i18n = getComposer(nuxtApp.$i18n as I18n)
const i18n = getComposer(nuxtApp.$i18n as unknown as I18n)
return joinURL(unref(i18n.baseUrl), nuxtApp.$config.app.baseURL)
}

Expand Down Expand Up @@ -211,11 +211,11 @@ export function getAlternateOgLocales(
return alternateLocales.map(locale => ({
[key]: `i18n-og-alt-${locale.language}`,
property: 'og:locale:alternate',
content: hypenToUnderscore(locale.language!)
content: hypenToUnderscore(locale.language)
}))
}

function hypenToUnderscore(str: string) {
function hypenToUnderscore(str?: string) {
return (str || '').replace(/-/g, '_')
}

Expand Down
6 changes: 4 additions & 2 deletions src/runtime/routing/compatibles/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { resolve, routeToObject } from './utils'
import { getLocaleRouteName, getRouteName } from '../utils'
import { extendPrefixable, extendSwitchLocalePathIntercepter, type CommonComposableOptions } from '../../utils'

import type { Strategies, PrefixableOptions, SwitchLocalePathIntercepter } from '#build/i18n.options.mjs'
import type { Strategies, PrefixableOptions, SwitchLocalePathIntercepter } from '../../../types'
import type { Locale } from 'vue-i18n'
import type {
RouteLocation,
Expand All @@ -20,6 +20,7 @@ import type {
RouteLocationNormalizedLoaded,
RouteLocationNormalized
} from 'vue-router'
import type { ModulePublicRuntimeConfig } from '~/src/module'

const RESOLVED_PREFIXED = new Set<Strategies>(['prefix_and_default', 'prefix_except_default'])

Expand Down Expand Up @@ -132,7 +133,8 @@ export function localeLocation(
export function resolveRoute(common: CommonComposableOptions, route: RouteLocationRaw, locale: Locale | undefined) {
const { router, i18n } = common
const _locale = locale || getLocale(i18n)
const { defaultLocale, strategy, trailingSlash } = common.runtimeConfig.public.i18n
const { defaultLocale, strategy, trailingSlash } = common.runtimeConfig.public
.i18n as ModulePublicRuntimeConfig['i18n']
const prefixable = extendPrefixable(common.runtimeConfig)
// if route parameter is a string, check if it's a path or name of route.
let _route: RouteLocationPathRaw | RouteLocationNamedRaw
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/routing/compatibles/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { assign } from '@intlify/shared'

import type { Locale } from 'vue-i18n'
import type { RouteLocationNormalizedLoaded, RouteLocationPathRaw } from 'vue-router'
import type { Strategies } from '#build/i18n.options.mjs'
import type { Strategies } from '../../../types'
import type { CommonComposableOptions } from '../../utils'

function split(str: string, index: number) {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/routing/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { isString, isSymbol, isFunction } from '@intlify/shared'

import type { LocaleObject, Strategies, BaseUrlResolveHandler } from '#build/i18n.options.mjs'
import type { LocaleObject, Strategies, BaseUrlResolveHandler } from '../../types'
import type { Locale } from 'vue-i18n'

export const inBrowser = typeof window !== 'undefined'
Expand Down
Loading
Loading