docs/ext/extensionRepos.data.ts
465 lines · 13447 bytes
1import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
2import { dirname, join } from 'node:path'
3import { fileURLToPath } from 'node:url'
4
5const IGNORED_DIRS = new Set(['node_modules', '.vitepress', '.git'])
6
7export type Rating = 'safe' | 'suggestive' | 'nsfw'
8
9export interface RepoSite {
10 name: string
11 lang: string
12 icon: string
13 url: string
14 rating: Rating
15 contentType?: string
16 isBroken?: boolean
17}
18
19export interface RepoData {
20 sites: RepoSite[]
21}
22
23interface MihonSource {
24 name: string
25 lang: string
26 baseUrl: string
27}
28
29interface MihonExtension {
30 pkg: string
31 nsfw?: number
32 sources?: MihonSource[]
33}
34
35interface AidokuSource {
36 name: string
37 iconURL: string
38 languages?: string[]
39 contentRating?: number
40 baseURL: string
41}
42
43interface AidokuIndex {
44 sources: AidokuSource[]
45}
46
47interface AidokuLegacySource {
48 name: string
49 icon: string
50 lang: string
51 nsfw?: number
52}
53
54interface PaperbackSource {
55 id: string
56 name: string
57 icon: string
58 language?: string
59 contentRating?: string
60 websiteBaseURL?: string
61}
62
63interface PaperbackIndex {
64 sources: PaperbackSource[]
65 builtWith?: { toolchain?: string }
66}
67
68interface CloudstreamRepo {
69 pluginLists: string[]
70}
71
72interface CloudstreamPlugin {
73 name: string
74 iconUrl?: string
75 language?: string
76}
77
78interface HayaseExtension {
79 name: string
80 icon?: string
81 languages?: string[]
82}
83
84interface LegadoBookSource {
85 bookSourceName: string
86 bookSourceUrl: string
87 bookSourceGroup?: string
88}
89
90interface LNReaderPlugin {
91 name: string
92 lang: string
93 url: string
94 iconUrl?: string
95}
96
97interface MangayomiSource {
98 name: string
99 lang: string
100 baseUrl: string
101 iconUrl?: string
102 isNsfw?: boolean
103}
104
105interface IReaderSource {
106 pkg: string
107 apk: string
108 name: string
109 lang: string
110 nsfw?: boolean
111}
112
113// For kotatsu
114interface KotatsuSite {
115 name: string
116 lang: string
117 url: string
118 icon: string
119 contentType: string
120 isBroken: boolean
121}
122
123interface KotatsuIndex {
124 sites: KotatsuSite[]
125}
126
127const EXT_DIR = dirname(fileURLToPath(import.meta.url))
128const DOCS_DIR = join(EXT_DIR, '..')
129const CACHE_DIR = join(EXT_DIR, '../.vitepress/cache/extension-repos')
130const CACHE_TTL_MS = 6 * 60 * 60 * 1000
131
132function findMarkdownFiles(dir: string): string[] {
133 const files: string[] = []
134 for (const entry of readdirSync(dir, { withFileTypes: true })) {
135 if (entry.isDirectory()) {
136 if (!IGNORED_DIRS.has(entry.name)) files.push(...findMarkdownFiles(join(dir, entry.name)))
137 } else if (entry.name.endsWith('.md')) {
138 files.push(join(dir, entry.name))
139 }
140 }
141 return files
142}
143
144function collectIndexUrls(): string[] {
145 const urls = new Set<string>()
146 const blockRe = /:::\s*extrepo[^\n]*\n([\s\S]*?)\n\s*:::/g
147 const rowRe = /^\s*-\s*(?:raw|manga|anime|novel)\s*:\s*(https?:\/\/\S+)\s*$/gim
148
149 for (const file of findMarkdownFiles(DOCS_DIR)) {
150 const src = readFileSync(file, 'utf-8')
151
152 let block: RegExpExecArray | null
153 blockRe.lastIndex = 0
154 while ((block = blockRe.exec(src))) {
155 rowRe.lastIndex = 0
156 let row: RegExpExecArray | null
157 while ((row = rowRe.exec(block[1]))) urls.add(row[1].trim())
158 }
159 }
160 return [...urls]
161}
162
163function cachePathFor(url: string): string {
164 return join(CACHE_DIR, `${Buffer.from(url).toString('base64url')}.json`)
165}
166
167async function fetchIndex(url: string): Promise<unknown> {
168 const cachePath = cachePathFor(url)
169 if (existsSync(cachePath) && Date.now() - statSync(cachePath).mtimeMs < CACHE_TTL_MS) {
170 return JSON.parse(readFileSync(cachePath, 'utf-8'))
171 }
172
173 try {
174 const res = await fetch(url)
175 if (!res.ok) throw new Error(`${res.status} ${res.statusText}`)
176 const json = await res.json()
177 mkdirSync(CACHE_DIR, { recursive: true })
178 writeFileSync(cachePath, JSON.stringify(json))
179 return json
180 } catch (err) {
181 if (existsSync(cachePath)) return JSON.parse(readFileSync(cachePath, 'utf-8'))
182 console.warn(`[extrepo] failed to fetch ${url}: ${(err as Error).message}`)
183 return []
184 }
185}
186
187function ratingFromLevel(level: number): Rating {
188 if (level >= 2) return 'nsfw'
189 if (level >= 1) return 'suggestive'
190 return 'safe'
191}
192
193const LANG_ALIASES: Record<string, string> = {
194 jp: 'ja',
195 english: 'en',
196 'bahasa indonesia': 'id',
197 español: 'es',
198 français: 'fr',
199 polski: 'pl',
200 português: 'pt',
201 'tiếng việt': 'vi',
202 türkçe: 'tr',
203 русский: 'ru',
204 українська: 'uk',
205 ไทย: 'th',
206 العربية: 'ar',
207 chinese: 'zh',
208 japanese: 'ja',
209 korean: 'ko'
210}
211
212const LANG_SUBSTRING_ALIASES: [RegExp, string][] = [
213 [/中文|汉语|漢語/, 'zh'],
214 [/日本語/, 'ja'],
215 [/한국어|조선말/, 'ko']
216]
217
218function normalizeLang(lang: string): string {
219 // Strip bidi control marks (e.g. U+200E/U+200F) some indices prepend to lang names.
220 const cleaned = lang.replace(/[]/g, '').trim()
221 if (cleaned === '') return 'all'
222 const exact = LANG_ALIASES[cleaned.toLowerCase()]
223 if (exact) return exact
224 for (const [re, code] of LANG_SUBSTRING_ALIASES) {
225 if (re.test(cleaned)) return code
226 }
227 const key = cleaned.toLowerCase()
228 return key === 'multi' ? 'all' : key
229}
230
231function toRepoDataMihon(iconBase: string, extensions: MihonExtension[]): RepoSite[] {
232 const seen = new Set<string>()
233 const sites: RepoSite[] = []
234
235 for (const ext of extensions) {
236 const icon = `${iconBase}/icon/${ext.pkg}.png`
237 for (const source of ext.sources ?? []) {
238 const key = `${source.name}::${source.lang}::${source.baseUrl}`
239 if (seen.has(key)) continue
240 seen.add(key)
241 sites.push({ name: source.name, lang: source.lang, icon, url: source.baseUrl, rating: ext.nsfw === 1 ? 'nsfw' : 'safe' })
242 }
243 }
244
245 return sites
246}
247
248function toRepoDataAidoku(iconBase: string, index: AidokuIndex): RepoSite[] {
249 const seen = new Set<string>()
250 const sites: RepoSite[] = []
251
252 for (const source of index.sources ?? []) {
253 const icon = `${iconBase}/${source.iconURL}`
254 const rating = ratingFromLevel(source.contentRating ?? 0)
255 const langs = source.languages?.length ? source.languages : ['all']
256 for (const rawLang of langs) {
257 const lang = normalizeLang(rawLang)
258 const key = `${source.name}::${lang}::${source.baseURL}`
259 if (seen.has(key)) continue
260 seen.add(key)
261 sites.push({ name: source.name, lang, icon, url: source.baseURL, rating })
262 }
263 }
264
265 return sites
266}
267
268function toRepoDataPaperback(iconBase: string, index: PaperbackIndex): RepoSite[] {
269 const seen = new Set<string>()
270 const sites: RepoSite[] = []
271 // Legacy 0.8.x toolchain builds serve icons under `<id>/includes/`
272 const iconDir = index.builtWith?.toolchain?.startsWith('0.8') ? 'includes' : 'static'
273
274 for (const source of index.sources ?? []) {
275 const lang = normalizeLang(source.language ?? 'all')
276 const key = `${source.id}::${lang}`
277 if (seen.has(key)) continue
278 seen.add(key)
279 const icon = `${iconBase}/${source.id}/${iconDir}/${source.icon}`
280 const rating: Rating = source.contentRating === 'ADULT' ? 'nsfw' : source.contentRating === 'MATURE' ? 'suggestive' : 'safe'
281 sites.push({ name: source.name, lang, icon, url: source.websiteBaseURL ?? '', rating })
282 }
283
284 return sites
285}
286
287function normalizeGoogleFaviconUrl(url: string): string {
288 return url.replace('%size%', '64')
289}
290
291async function toRepoDataCloudstream(repo: CloudstreamRepo): Promise<RepoSite[]> {
292 const seen = new Set<string>()
293 const sites: RepoSite[] = []
294
295 const lists = await Promise.all(repo.pluginLists.map(url => fetchIndex(url)))
296 for (const list of lists) {
297 if (!Array.isArray(list)) continue
298 for (const plugin of list as CloudstreamPlugin[]) {
299 if (seen.has(plugin.name)) continue
300 seen.add(plugin.name)
301 const lang = normalizeLang(plugin.language ?? 'all')
302 const icon = plugin.iconUrl ? normalizeGoogleFaviconUrl(plugin.iconUrl) : ''
303 sites.push({ name: plugin.name, lang, icon, url: '', rating: 'safe' })
304 }
305 }
306
307 return sites
308}
309
310function toRepoDataAidokuLegacy(iconBase: string, sources: AidokuLegacySource[]): RepoSite[] {
311 const seen = new Set<string>()
312 const sites: RepoSite[] = []
313
314 for (const source of sources) {
315 const lang = normalizeLang(source.lang)
316 const key = `${source.name}::${lang}`
317 if (seen.has(key)) continue
318 seen.add(key)
319 sites.push({ name: source.name, lang, icon: `${iconBase}/icons/${source.icon}`, url: '', rating: ratingFromLevel(source.nsfw ?? 0) })
320 }
321
322 return sites
323}
324
325function toRepoDataHayase(extensions: HayaseExtension[]): RepoSite[] {
326 const seen = new Set<string>()
327 const sites: RepoSite[] = []
328
329 for (const ext of extensions) {
330 const langs = ext.languages?.length ? ext.languages : ['all']
331 for (const rawLang of langs) {
332 const lang = normalizeLang(rawLang)
333 const key = `${ext.name}::${lang}`
334 if (seen.has(key)) continue
335 seen.add(key)
336 sites.push({ name: ext.name, lang, icon: ext.icon ?? '', url: '', rating: 'safe' })
337 }
338 }
339
340 return sites
341}
342
343function toRepoDataLegado(sources: LegadoBookSource[]): RepoSite[] {
344 const seen = new Set<string>()
345 const sites: RepoSite[] = []
346
347 for (const source of sources) {
348 const lang = normalizeLang(source.bookSourceGroup ?? 'all')
349 const key = `${source.bookSourceName}::${lang}`
350 if (seen.has(key)) continue
351 seen.add(key)
352 sites.push({ name: source.bookSourceName, lang, icon: '', url: source.bookSourceUrl, rating: 'safe' })
353 }
354
355 return sites
356}
357
358function toRepoDataMangayomi(sources: MangayomiSource[]): RepoSite[] {
359 const seen = new Set<string>()
360 const sites: RepoSite[] = []
361
362 for (const source of sources) {
363 const lang = normalizeLang(source.lang)
364 const key = `${source.name}::${lang}`
365 if (seen.has(key)) continue
366 seen.add(key)
367 sites.push({ name: source.name, lang, icon: source.iconUrl ?? '', url: source.baseUrl, rating: source.isNsfw ? 'nsfw' : 'safe' })
368 }
369
370 return sites
371}
372
373function toRepoDataIReader(sources: IReaderSource[]): RepoSite[] {
374 const seen = new Set<string>()
375 const sites: RepoSite[] = []
376
377 for (const source of sources) {
378 const lang = normalizeLang(source.lang)
379 const key = `${source.name}::${lang}`
380 if (seen.has(key)) continue
381 seen.add(key)
382 // No confirmed icon path convention in this repo's format — omit rather than guess wrong.
383 sites.push({ name: source.name, lang, icon: '', url: '', rating: source.nsfw ? 'nsfw' : 'safe' })
384 }
385
386 return sites
387}
388
389function toRepoDataKotatsu(index: KotatsuIndex): RepoSite[] {
390 const seen = new Set<string>()
391 const sites: RepoSite[] = []
392
393 for (const site of index.sites) {
394 const lang = normalizeLang(site.lang)
395 const key = `${site.name}::${lang}::${site.url}`
396 if (seen.has(key)) continue
397 seen.add(key)
398 const rating: Rating = site.contentType.includes('HENTAI') ? 'nsfw' : 'safe'
399 sites.push({ name: site.name, lang, icon: site.icon, url: site.url, rating, contentType: site.contentType, isBroken: site.isBroken || undefined })
400 }
401
402 return sites
403}
404
405function toRepoDataLNReader(plugins: LNReaderPlugin[]): RepoSite[] {
406 const seen = new Set<string>()
407 const sites: RepoSite[] = []
408
409 for (const plugin of plugins) {
410 const lang = normalizeLang(plugin.lang)
411 const key = `${plugin.name}::${lang}`
412 if (seen.has(key)) continue
413 seen.add(key)
414 sites.push({ name: plugin.name, lang, icon: plugin.iconUrl ?? '', url: plugin.url, rating: 'safe' })
415 }
416
417 return sites
418}
419
420async function toRepoData(indexUrl: string, json: unknown): Promise<RepoData> {
421 const iconBase = indexUrl.slice(0, indexUrl.lastIndexOf('/'))
422 let sites: RepoSite[]
423 if (Array.isArray(json)) {
424 const first = json[0] as Record<string, unknown> | undefined
425 if (first && 'bookSourceUrl' in first) {
426 sites = toRepoDataLegado(json as LegadoBookSource[])
427 } else if (first && 'manifestVersion' in first) {
428 sites = toRepoDataHayase(json as HayaseExtension[])
429 } else if (first && 'iconUrl' in first && 'site' in first) {
430 sites = toRepoDataLNReader(json as LNReaderPlugin[])
431 } else if (first && 'sources' in first) {
432 sites = toRepoDataMihon(iconBase, json as MihonExtension[])
433 } else if (first && 'pkg' in first && 'apk' in first) {
434 sites = toRepoDataIReader(json as IReaderSource[])
435 } else if (first && 'iconUrl' in first && 'baseUrl' in first) {
436 sites = toRepoDataMangayomi(json as MangayomiSource[])
437 } else {
438 sites = toRepoDataAidokuLegacy(iconBase, json as AidokuLegacySource[])
439 }
440 } else if (Array.isArray((json as CloudstreamRepo).pluginLists)) {
441 sites = await toRepoDataCloudstream(json as CloudstreamRepo)
442 } else if ((json as AidokuIndex).sources?.length && 'iconURL' in (json as AidokuIndex).sources[0]) {
443 sites = toRepoDataAidoku(iconBase, json as AidokuIndex)
444 } else if (Array.isArray((json as KotatsuIndex).sites)) {
445 sites = toRepoDataKotatsu(json as KotatsuIndex)
446 } else {
447 sites = toRepoDataPaperback(iconBase, json as PaperbackIndex)
448 }
449 sites.sort((a, b) => a.name.localeCompare(b.name))
450 return { sites }
451}
452
453export declare const data: Record<string, RepoData>
454
455export default {
456 watch: ['../**/*.md'],
457 async load(): Promise<Record<string, RepoData>> {
458 const urls = collectIndexUrls()
459 const result: Record<string, RepoData> = {}
460 await Promise.all(urls.map(async url => {
461 result[url] = await toRepoData(url, await fetchIndex(url))
462 }))
463 return result
464 }
465}