-
Notifications
You must be signed in to change notification settings - Fork 463
/
gen.ts
199 lines (163 loc) · 6.17 KB
/
gen.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/* eslint-disable @typescript-eslint/no-explicit-any */
import createDebug from 'debug'
import { EXECUTABLE_EXTENSIONS } from './constants'
import { genImport, genDynamicImport } from 'knitwork'
import { withQuery } from 'ufo'
import { resolve, relative, join } from 'pathe'
import { distDir, runtimeDir } from './dirs'
import { getLayerI18n, getLocalePaths, toCode } from './utils'
import type { Nuxt } from '@nuxt/schema'
import type { PrerenderTarget } from './utils'
import type { NuxtI18nOptions, LocaleInfo, VueI18nConfigPathInfo, FileMeta, LocaleObject } from './types'
export type LoaderOptions = {
vueI18nConfigPaths: Required<VueI18nConfigPathInfo>[]
localeInfo: LocaleInfo[]
nuxtI18nOptions: NuxtI18nOptions
isServer: boolean
}
const debug = createDebug('@nuxtjs/i18n:gen')
const generateVueI18nConfiguration = (config: Required<VueI18nConfigPathInfo>, isServer = false): string => {
return genDynamicImport(
genImportSpecifier({ ...config.meta, isServer }, 'config'),
!isServer
? {
comment: `webpackChunkName: "${config.meta.key}"`
}
: {}
)
}
function simplifyLocaleOptions(nuxt: Nuxt, options: NuxtI18nOptions) {
const isLocaleObjectsArray = (locales?: string[] | LocaleObject[]) => locales?.some(x => typeof x !== 'string')
const hasLocaleObjects =
nuxt.options._layers.some(layer => isLocaleObjectsArray(getLayerI18n(layer)?.locales)) ||
options?.i18nModules?.some(module => isLocaleObjectsArray(module?.locales))
const locales = (options.locales ?? []) as LocaleObject[]
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return locales.map(({ meta, ...locale }) => {
if (!hasLocaleObjects) {
return locale.code
}
if (locale.file || (locale.files?.length ?? 0) > 0) {
locale.files = getLocalePaths(locale)
} else {
delete locale.files
}
delete locale.file
return locale
})
}
export function generateLoaderOptions(
nuxt: Nuxt,
{ nuxtI18nOptions, vueI18nConfigPaths, localeInfo, isServer }: LoaderOptions
) {
debug('generateLoaderOptions: lazy', nuxtI18nOptions.lazy)
const importMapper = new Map<string, { key: string; load: string; cache: string }>()
const importStrings: string[] = []
function generateLocaleImports(locale: string, meta: NonNullable<LocaleInfo['meta']>[number], isServer = false) {
if (importMapper.has(meta.key)) return
const importSpecifier = genImportSpecifier({ ...meta, isServer }, 'locale', { locale })
const importer = { code: locale, key: meta.loadPath, load: '', cache: meta.file.cache ?? true }
if (nuxtI18nOptions.lazy) {
importer.load = genDynamicImport(importSpecifier, !isServer ? { comment: `webpackChunkName: "${meta.key}"` } : {})
} else {
importStrings.push(genImport(importSpecifier, meta.key))
importer.load = `() => Promise.resolve(${meta.key})`
}
importMapper.set(meta.key, {
key: toCode(importer?.key),
load: importer?.load,
cache: toCode(importer?.cache)
})
}
/**
* Prepare locale file imports
*/
for (const locale of localeInfo) {
locale?.meta?.forEach(meta => generateLocaleImports(locale.code, meta, isServer))
}
/**
* Prepare Vue I18n config imports
*/
const vueI18nConfigImports = [...vueI18nConfigPaths]
.reverse()
.filter(config => config.absolute !== '')
.map(config => generateVueI18nConfiguration(config, isServer))
const localeLoaders = localeInfo.map(locale => [locale.code, locale.meta?.map(meta => importMapper.get(meta.key))])
const generatedNuxtI18nOptions = {
...nuxtI18nOptions,
locales: simplifyLocaleOptions(nuxt, nuxtI18nOptions)
}
delete nuxtI18nOptions.vueI18n
const generated = {
importStrings,
localeLoaders,
nuxtI18nOptions: generatedNuxtI18nOptions,
vueI18nConfigs: vueI18nConfigImports
}
debug('generate code', generated)
return generated
}
function genImportSpecifier(
{
loadPath,
path,
parsed,
hash,
type,
isServer
}: Pick<FileMeta, 'loadPath' | 'path' | 'parsed' | 'hash' | 'type'> & { isServer?: boolean },
resourceType: PrerenderTarget['type'] | undefined,
query: Record<string, string> = {}
) {
const getLoadPath = () => (!isServer ? loadPath : path)
if (!EXECUTABLE_EXTENSIONS.includes(parsed.ext)) {
return getLoadPath()
}
if (resourceType != null && type === 'unknown') {
throw new Error(`'unknown' type in '${path}'.`)
}
if (resourceType === 'locale') {
return !isServer ? withQuery(getLoadPath(), type === 'dynamic' ? { hash, ...query } : {}) : getLoadPath()
}
if (resourceType === 'config') {
return !isServer ? withQuery(getLoadPath(), { hash, ...query, ...{ config: 1 } }) : getLoadPath()
}
return getLoadPath()
}
export function generateI18nPageTypes() {
return `// Generated by @nuxtjs/i18n
declare module 'nuxt/dist/pages/runtime' {
interface PageMeta {
nuxtI18n?: Record<string, any>
}
}
export {}`
}
export function generateI18nTypes(nuxt: Nuxt, options: NuxtI18nOptions) {
const vueI18nTypes = options.types === 'legacy' ? ['VueI18n'] : ['ExportedGlobalComposer', 'Composer']
const generatedLocales = simplifyLocaleOptions(nuxt, options)
const resolvedLocaleType = typeof generatedLocales === 'string' ? 'string[]' : 'LocaleObject[]'
// prettier-ignore
return `// Generated by @nuxtjs/i18n
import type { ${vueI18nTypes.join(', ')} } from 'vue-i18n'
import type { NuxtI18nRoutingCustomProperties, ComposerCustomProperties } from '${relative(
join(nuxt.options.buildDir, 'types'),
resolve(runtimeDir, 'types.ts')
)}'
import type { Strategies, Directions, LocaleObject } from '${relative(
join(nuxt.options.buildDir, 'types'),
resolve(distDir, 'types.d.ts')
)}'
declare module 'vue-i18n' {
interface ComposerCustom extends ComposerCustomProperties<${resolvedLocaleType}> {}
interface ExportedGlobalComposer extends NuxtI18nRoutingCustomProperties<${resolvedLocaleType}> {}
interface VueI18n extends NuxtI18nRoutingCustomProperties<${resolvedLocaleType}> {}
}
declare module '#app' {
interface NuxtApp {
$i18n: ${vueI18nTypes.join(' & ')} & NuxtI18nRoutingCustomProperties<${resolvedLocaleType}>
}
}
export {}`
}
/* eslint-enable @typescript-eslint/no-explicit-any */