This repository has been archived by the owner on Aug 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 155
/
nuxt.config.ts
409 lines (361 loc) · 11.8 KB
/
nuxt.config.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import { promises as fs } from 'fs'
import { pathToFileURL } from 'node:url'
import svgLoader from 'vite-svg-loader'
import { resolve, basename, relative } from 'pathe'
import { defineNuxtConfig } from 'nuxt/config'
import { $fetch } from 'ofetch'
import { globIterate } from 'glob'
import { match as matchLocale } from '@formatjs/intl-localematcher'
import { consola } from 'consola'
const STAGING_API_URL = 'https://staging-api.modrinth.com/v2/'
const preloadedFonts = [
'inter/Inter-Regular.woff2',
'inter/Inter-Medium.woff2',
'inter/Inter-SemiBold.woff2',
'inter/Inter-Bold.woff2',
]
const favicons = {
'(prefers-color-scheme:no-preference)': '/favicon-light.ico',
'(prefers-color-scheme:light)': '/favicon-light.ico',
'(prefers-color-scheme:dark)': '/favicon.ico',
}
/**
* Tags of locales that are auto-discovered besides the default locale.
*
* Preferably only the locales that reach a certain threshold of complete
* translations would be included in this array.
*/
const enabledLocales: string[] = []
/**
* Overrides for the categories of the certain locales.
*/
const localesCategoriesOverrides: Partial<Record<string, 'fun' | 'experimental'>> = {
'en-x-pirate': 'fun',
'en-x-updown': 'fun',
'en-x-lolcat': 'fun',
'en-x-uwu': 'fun',
'ru-x-bandit': 'fun',
ar: 'experimental',
he: 'experimental',
pes: 'experimental',
}
export default defineNuxtConfig({
app: {
head: {
htmlAttrs: {
lang: 'en',
},
title: 'Modrinth',
link: [
// The type is necessary because the linter can't always compare this very nested/complex type on itself
...preloadedFonts.map((font): object => {
return {
rel: 'preload',
href: `https://cdn-raw.modrinth.com/fonts/${font}?v=3.19`,
as: 'font',
type: 'font/woff2',
crossorigin: 'anonymous',
}
}),
...Object.entries(favicons).map(([media, href]): object => {
return { rel: 'icon', type: 'image/x-icon', href, media }
}),
...Object.entries(favicons).map(([media, href]): object => {
return { rel: 'apple-touch-icon', type: 'image/x-icon', href, media, sizes: '64x64' }
}),
{
rel: 'search',
type: 'application/opensearchdescription+xml',
href: '/opensearch.xml',
title: 'Modrinth mods',
},
],
},
},
vite: {
plugins: [
svgLoader({
svgoConfig: {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
},
},
},
],
},
}),
],
},
hooks: {
async 'build:before'() {
// 30 minutes
const TTL = 30 * 60 * 1000
let state: {
lastGenerated?: string
apiUrl?: string
categories?: any[]
loaders?: any[]
gameVersions?: any[]
donationPlatforms?: any[]
reportTypes?: any[]
} = {}
try {
state = JSON.parse(await fs.readFile('./generated/state.json', 'utf8'))
} catch {
// File doesn't exist, create folder
await fs.mkdir('./generated', { recursive: true })
}
const API_URL = getApiUrl()
if (
// Skip regeneration if within TTL...
state.lastGenerated &&
new Date(state.lastGenerated).getTime() + TTL > new Date().getTime() &&
// ...but only if the API URL is the same
state.apiUrl === API_URL
) {
return
}
state.lastGenerated = new Date().toISOString()
state.apiUrl = API_URL
const headers = {
headers: {
'user-agent': 'Knossos generator ([email protected])',
},
}
const [categories, loaders, gameVersions, donationPlatforms, reportTypes] = await Promise.all(
[
$fetch(`${API_URL}tag/category`, headers),
$fetch(`${API_URL}tag/loader`, headers),
$fetch(`${API_URL}tag/game_version`, headers),
$fetch(`${API_URL}tag/donation_platform`, headers),
$fetch(`${API_URL}tag/report_type`, headers),
]
)
state.categories = categories
state.loaders = loaders
state.gameVersions = gameVersions
state.donationPlatforms = donationPlatforms
state.reportTypes = reportTypes
await fs.writeFile('./generated/state.json', JSON.stringify(state))
console.log('Tags generated!')
},
'pages:extend'(routes) {
routes.splice(
routes.findIndex((x) => x.name === 'search-searchProjectType'),
1
)
const types = ['mods', 'modpacks', 'plugins', 'resourcepacks', 'shaders', 'datapacks']
types.forEach((type) =>
routes.push({
name: `search-${type}`,
path: `/${type}`,
file: resolve(__dirname, 'pages/search/[searchProjectType].vue'),
children: [],
})
)
},
async 'vintl:extendOptions'(opts) {
opts.locales ??= []
const isProduction = getDomain() === 'https://modrinth.com'
const resolveCompactNumberDataImport = await (async () => {
const compactNumberLocales: string[] = []
for await (const localeFile of globIterate(
'node_modules/@vintl/compact-number/dist/locale-data/*.mjs',
{ ignore: '**/*.data.mjs' }
)) {
const tag = basename(localeFile, '.mjs')
compactNumberLocales.push(tag)
}
function resolveImport(tag: string) {
const matchedTag = matchLocale([tag], compactNumberLocales, 'en-x-placeholder')
return matchedTag === 'en-x-placeholder'
? undefined
: `@vintl/compact-number/locale-data/${matchedTag}`
}
return resolveImport
})()
const resolveOmorphiaLocaleImport = await (async () => {
const omorphiaLocales: string[] = []
const omorphiaLocaleSets = new Map<string, { files: { from: string }[] }>()
for await (const localeDir of globIterate('node_modules/omorphia/locales/*', {
posix: true,
})) {
const tag = basename(localeDir)
omorphiaLocales.push(tag)
const localeFiles: { from: string; format?: string }[] = []
omorphiaLocaleSets.set(tag, { files: localeFiles })
for await (const localeFile of globIterate(`${localeDir}/*`, { posix: true })) {
localeFiles.push({
from: pathToFileURL(localeFile).toString(),
format: 'default',
})
}
}
return function resolveLocaleImport(tag: string) {
return omorphiaLocaleSets.get(matchLocale([tag], omorphiaLocales, 'en-x-placeholder'))
}
})()
for await (const localeDir of globIterate('locales/*/', { posix: true })) {
const tag = basename(localeDir)
if (isProduction && !enabledLocales.includes(tag) && opts.defaultLocale !== tag) continue
const locale =
opts.locales.find((locale) => locale.tag === tag) ??
opts.locales[opts.locales.push({ tag }) - 1]
const localeFiles = (locale.files ??= [])
for await (const localeFile of globIterate(`${localeDir}/*`, { posix: true })) {
const fileName = basename(localeFile)
if (fileName === 'index.json') {
localeFiles.push({
from: `./${localeFile}`,
format: 'crowdin',
})
} else if (fileName === 'meta.json') {
const meta: Record<string, { message: string }> = await fs
.readFile(localeFile, 'utf8')
.then((date) => JSON.parse(date))
locale.meta ??= {}
for (const key in meta) {
locale.meta[key] = meta[key].message
}
} else {
;(locale.resources ??= {})[fileName] = `./${localeFile}`
}
}
const categoryOverride = localesCategoriesOverrides[tag]
if (categoryOverride != null) {
;(locale.meta ??= {}).category = categoryOverride
}
const omorphiaLocaleData = resolveOmorphiaLocaleImport(tag)
if (omorphiaLocaleData != null) {
localeFiles.push(...omorphiaLocaleData.files)
}
const cnDataImport = resolveCompactNumberDataImport(tag)
if (cnDataImport != null) {
;(locale.additionalImports ??= []).push({
from: cnDataImport,
resolve: false,
})
}
}
},
},
runtimeConfig: {
// @ts-ignore
apiBaseUrl: process.env.BASE_URL ?? globalThis.BASE_URL ?? getApiUrl(),
// @ts-ignore
rateLimitKey: process.env.RATE_LIMIT_IGNORE_KEY ?? globalThis.RATE_LIMIT_IGNORE_KEY,
public: {
apiBaseUrl: getApiUrl(),
siteUrl: getDomain(),
production: isProduction(),
featureFlagOverrides: getFeatureFlagOverrides(),
owner: process.env.VERCEL_GIT_REPO_OWNER || 'modrinth',
slug: process.env.VERCEL_GIT_REPO_SLUG || 'knossos',
branch:
process.env.VERCEL_GIT_COMMIT_REF ||
process.env.CF_PAGES_BRANCH ||
// @ts-ignore
globalThis.CF_PAGES_BRANCH ||
'master',
hash:
process.env.VERCEL_GIT_COMMIT_SHA ||
process.env.CF_PAGES_COMMIT_SHA ||
// @ts-ignore
globalThis.CF_PAGES_COMMIT_SHA ||
'unknown',
turnstile: { siteKey: '0x4AAAAAAAW3guHM6Eunbgwu' },
},
},
typescript: {
shim: false,
strict: true,
typeCheck: true,
tsConfig: {
compilerOptions: {
moduleResolution: 'bundler',
allowImportingTsExtensions: true,
},
},
},
modules: ['@vintl/nuxt', '@nuxtjs/turnstile'],
vintl: {
defaultLocale: 'en-US',
locales: [
{
tag: 'en-US',
meta: {
static: {
iso: 'en',
},
},
},
],
storage: 'cookie',
parserless: 'only-prod',
seo: {
defaultLocaleHasParameter: false,
},
onParseError({ error, message, messageId, moduleId, parseMessage, parserOptions }) {
const errorMessage = String(error)
const modulePath = relative(__dirname, moduleId)
try {
const fallback = parseMessage(message, { ...parserOptions, ignoreTag: true })
consola.warn(
`[i18n] ${messageId} in ${modulePath} cannot be parsed normally due to ${errorMessage}. The tags will will not be parsed.`
)
return fallback
} catch (err) {
const secondaryErrorMessage = String(err)
const reason =
errorMessage === secondaryErrorMessage
? errorMessage
: `${errorMessage} and ${secondaryErrorMessage}`
consola.warn(
`[i18n] ${messageId} in ${modulePath} cannot be parsed due to ${reason}. It will be skipped.`
)
}
},
},
nitro: {
moduleSideEffects: ['@vintl/compact-number/locale-data'],
},
devtools: {
enabled: true,
},
})
function getApiUrl() {
// @ts-ignore
return process.env.BROWSER_BASE_URL ?? globalThis.BROWSER_BASE_URL ?? STAGING_API_URL
}
function isProduction() {
return process.env.NODE_ENV === 'production'
}
function getFeatureFlagOverrides() {
return JSON.parse(process.env.FLAG_OVERRIDES ?? '{}')
}
function getDomain() {
if (process.env.NODE_ENV === 'production') {
if (process.env.SITE_URL) {
return process.env.SITE_URL
}
// @ts-ignore
else if (process.env.CF_PAGES_URL || globalThis.CF_PAGES_URL) {
// @ts-ignore
return process.env.CF_PAGES_URL ?? globalThis.CF_PAGES_URL
} else if (process.env.HEROKU_APP_NAME) {
return `https://${process.env.HEROKU_APP_NAME}.herokuapp.com`
} else if (process.env.VERCEL_URL) {
return `https://${process.env.VERCEL_URL}`
} else if (getApiUrl() === STAGING_API_URL) {
return 'https://staging.modrinth.com'
} else {
return 'https://modrinth.com'
}
} else {
return 'http://localhost:3000'
}
}