docs/ext/extensionRepos.data.ts

dc37a0812a9971107e75ecfdb141c3d5bf0289fc
wotaku/docs/ext/extensionRepos.data.ts history · blame · raw

652 lines · 19276 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  installUrl?: string
 18}
 19
 20export interface RepoData {
 21  sites: RepoSite[]
 22  suwatteV6?: boolean
 23  suwatteListUrl?: string
 24}
 25
 26interface MihonSource {
 27  name: string
 28  lang: string
 29  baseUrl: string
 30}
 31
 32interface MihonExtension {
 33  pkg: string
 34  nsfw?: number
 35  sources?: MihonSource[]
 36}
 37
 38interface AidokuSource {
 39  name: string
 40  iconURL: string
 41  languages?: string[]
 42  contentRating?: number
 43  baseURL: string
 44}
 45
 46interface AidokuIndex {
 47  sources: AidokuSource[]
 48}
 49
 50interface AidokuLegacySource {
 51  name: string
 52  icon: string
 53  lang: string
 54  nsfw?: number
 55}
 56
 57interface PaperbackSource {
 58  id: string
 59  name: string
 60  icon: string
 61  language?: string
 62  contentRating?: string
 63  websiteBaseURL?: string
 64}
 65
 66interface PaperbackIndex {
 67  sources: PaperbackSource[]
 68  builtWith?: { toolchain?: string }
 69}
 70
 71interface CloudstreamRepo {
 72  pluginLists: string[]
 73}
 74
 75interface CloudstreamPlugin {
 76  name: string
 77  iconUrl?: string
 78  language?: string
 79}
 80
 81interface HayaseExtension {
 82  name: string
 83  icon?: string
 84  languages?: string[]
 85}
 86
 87interface LegadoBookSource {
 88  bookSourceName: string
 89  bookSourceUrl: string
 90  bookSourceGroup?: string
 91}
 92
 93interface LNReaderPlugin {
 94  name: string
 95  lang: string
 96  url: string
 97  iconUrl?: string
 98}
 99
100interface MangayomiSource {
101  name: string
102  lang: string
103  baseUrl: string
104  iconUrl?: string
105  isNsfw?: boolean
106}
107
108interface IReaderSource {
109  pkg: string
110  apk: string
111  name: string
112  lang: string
113  nsfw?: boolean
114}
115
116interface SuwatteCatalogSource {
117  name: string
118  website?: string
119  languages?: string[]
120  thumbnail?: string
121  path?: string
122}
123
124interface SuwatteCatalogIndex {
125  listUrl?: string
126  catalogVersion?: number
127  sources: SuwatteCatalogSource[]
128}
129
130// For kotatsu
131interface KotatsuSite {
132  name: string
133  lang: string
134  url: string
135  icon: string
136  contentType: string
137  isBroken: boolean
138}
139
140interface KotatsuIndex {
141  sites: KotatsuSite[]
142}
143
144interface SoraLibraryModule {
145  sourceName: string
146  iconUrl?: string
147  iconURL?: string
148  language?: string
149  languageClean?: string
150  baseUrl?: string
151  scriptUrl?: string
152  scriptURL?: string
153  manifestUrl?: string
154  jsonUrl?: string
155}
156
157interface SoraLibraryAuthor {
158  author: string
159  repo: string
160  types: Record<string, SoraLibraryModule[]>
161}
162
163export interface SoraTypeGroup {
164  label: string
165  indexUrl: string
166}
167
168export interface SoraAuthorRepo {
169  label: string
170  repoUrl?: string
171  types: SoraTypeGroup[]
172}
173
174const EXT_DIR = dirname(fileURLToPath(import.meta.url))
175const DOCS_DIR = join(EXT_DIR, '..')
176const CACHE_DIR = join(EXT_DIR, '../.vitepress/cache/extension-repos')
177const CACHE_TTL_MS = 6 * 60 * 60 * 1000
178
179function findMarkdownFiles(dir: string): string[] {
180  const files: string[] = []
181  for (const entry of readdirSync(dir, { withFileTypes: true })) {
182    if (entry.isDirectory()) {
183      if (!IGNORED_DIRS.has(entry.name)) files.push(...findMarkdownFiles(join(dir, entry.name)))
184    } else if (entry.name.endsWith('.md')) {
185      files.push(join(dir, entry.name))
186    }
187  }
188  return files
189}
190
191function collectIndexUrls(): string[] {
192  const urls = new Set<string>()
193  const blockRe = /:::\s*extrepo[^\n]*\n([\s\S]*?)\n\s*:::/g
194  const rowRe = /^\s*-\s*(?:raw|manga|anime|novel)\s*:\s*(https?:\/\/\S+)\s*$/gim
195
196  for (const file of findMarkdownFiles(DOCS_DIR)) {
197    const src = readFileSync(file, 'utf-8')
198
199    let block: RegExpExecArray | null
200    blockRe.lastIndex = 0
201    while ((block = blockRe.exec(src))) {
202      rowRe.lastIndex = 0
203      let row: RegExpExecArray | null
204      while ((row = rowRe.exec(block[1]))) urls.add(row[1].trim())
205    }
206  }
207  return [...urls]
208}
209
210function cachePathFor(url: string): string {
211  return join(CACHE_DIR, `${Buffer.from(url).toString('base64url')}.json`)
212}
213
214async function fetchIndex(url: string): Promise<unknown> {
215  const cachePath = cachePathFor(url)
216  if (existsSync(cachePath) && Date.now() - statSync(cachePath).mtimeMs < CACHE_TTL_MS) {
217    return JSON.parse(readFileSync(cachePath, 'utf-8'))
218  }
219
220  try {
221    const res = await fetch(url)
222    if (!res.ok) throw new Error(`${res.status} ${res.statusText}`)
223    const json = await res.json()
224    mkdirSync(CACHE_DIR, { recursive: true })
225    writeFileSync(cachePath, JSON.stringify(json))
226    return json
227  } catch (err) {
228    if (existsSync(cachePath)) return JSON.parse(readFileSync(cachePath, 'utf-8'))
229    console.warn(`[extrepo] failed to fetch ${url}: ${(err as Error).message}`)
230    return []
231  }
232}
233
234function ratingFromLevel(level: number): Rating {
235  if (level >= 2) return 'nsfw'
236  if (level >= 1) return 'suggestive'
237  return 'safe'
238}
239
240const LANG_ALIASES: Record<string, string> = {
241  jp: 'ja',
242  english: 'en',
243  'bahasa indonesia': 'id',
244  español: 'es',
245  français: 'fr',
246  polski: 'pl',
247  português: 'pt',
248  'tiếng việt': 'vi',
249  türkçe: 'tr',
250  русский: 'ru',
251  українська: 'uk',
252  ไทย: 'th',
253  العربية: 'ar',
254  chinese: 'zh',
255  japanese: 'ja',
256  korean: 'ko',
257  french: 'fr',
258  german: 'de',
259  greek: 'el',
260  indonesian: 'id',
261  italian: 'it',
262  spanish: 'es',
263  turkish: 'tr',
264  polish: 'pl',
265  russian: 'ru',
266  portuguese: 'pt',
267  arabic: 'ar',
268  tamil: 'ta',
269  ukrainian: 'uk',
270  vietnamese: 'vi',
271  thai: 'th',
272  hindi: 'hi',
273  malay: 'ms',
274  serbian: 'sr'
275}
276
277const LANG_SUBSTRING_ALIASES: [RegExp, string][] = [
278  [/中文|汉语|漢語/, 'zh'],
279  [/日本語/, 'ja'],
280  [/한국어|조선말/, 'ko']
281]
282
283function normalizeLang(lang: string): string {
284  // Strip bidi control marks (e.g. U+200E/U+200F) some indices prepend to lang names.
285  const cleaned = lang.replace(/[‎‏]/g, '').trim()
286  if (cleaned === '') return 'all'
287  const exact = LANG_ALIASES[cleaned.toLowerCase()]
288  if (exact) return exact
289  for (const [re, code] of LANG_SUBSTRING_ALIASES) {
290    if (re.test(cleaned)) return code
291  }
292  const key = cleaned.toLowerCase()
293  return key === 'multi' ? 'all' : key
294}
295
296function toRepoDataMihon(iconBase: string, extensions: MihonExtension[]): RepoSite[] {
297  const seen = new Set<string>()
298  const sites: RepoSite[] = []
299
300  for (const ext of extensions) {
301    const icon = `${iconBase}/icon/${ext.pkg}.png`
302    for (const source of ext.sources ?? []) {
303      const key = `${source.name}::${source.lang}::${source.baseUrl}`
304      if (seen.has(key)) continue
305      seen.add(key)
306      sites.push({ name: source.name, lang: source.lang, icon, url: source.baseUrl, rating: ext.nsfw === 1 ? 'nsfw' : 'safe' })
307    }
308  }
309
310  return sites
311}
312
313function toRepoDataAidoku(iconBase: string, index: AidokuIndex): RepoSite[] {
314  const seen = new Set<string>()
315  const sites: RepoSite[] = []
316
317  for (const source of index.sources ?? []) {
318    const icon = `${iconBase}/${source.iconURL}`
319    const rating = ratingFromLevel(source.contentRating ?? 0)
320    const langs = source.languages?.length ? source.languages : ['all']
321    for (const rawLang of langs) {
322      const lang = normalizeLang(rawLang)
323      const key = `${source.name}::${lang}::${source.baseURL}`
324      if (seen.has(key)) continue
325      seen.add(key)
326      sites.push({ name: source.name, lang, icon, url: source.baseURL, rating })
327    }
328  }
329
330  return sites
331}
332
333function toRepoDataPaperback(iconBase: string, index: PaperbackIndex): RepoSite[] {
334  const seen = new Set<string>()
335  const sites: RepoSite[] = []
336  // Legacy 0.8.x toolchain builds serve icons under `<id>/includes/`
337  const iconDir = index.builtWith?.toolchain?.startsWith('0.8') ? 'includes' : 'static'
338
339  for (const source of index.sources ?? []) {
340    const lang = normalizeLang(source.language ?? 'all')
341    const key = `${source.id}::${lang}`
342    if (seen.has(key)) continue
343    seen.add(key)
344    const icon = `${iconBase}/${source.id}/${iconDir}/${source.icon}`
345    const rating: Rating = source.contentRating === 'ADULT' ? 'nsfw' : source.contentRating === 'MATURE' ? 'suggestive' : 'safe'
346    sites.push({ name: source.name, lang, icon, url: source.websiteBaseURL ?? '', rating })
347  }
348
349  return sites
350}
351
352function normalizeGoogleFaviconUrl(url: string): string {
353  return url.replace('%size%', '64')
354}
355
356async function toRepoDataCloudstream(repo: CloudstreamRepo): Promise<RepoSite[]> {
357  const seen = new Set<string>()
358  const sites: RepoSite[] = []
359
360  const lists = await Promise.all(repo.pluginLists.map(url => fetchIndex(url)))
361  for (const list of lists) {
362    if (!Array.isArray(list)) continue
363    for (const plugin of list as CloudstreamPlugin[]) {
364      if (seen.has(plugin.name)) continue
365      seen.add(plugin.name)
366      const lang = normalizeLang(plugin.language ?? 'all')
367      const icon = plugin.iconUrl ? normalizeGoogleFaviconUrl(plugin.iconUrl) : ''
368      sites.push({ name: plugin.name, lang, icon, url: '', rating: 'safe' })
369    }
370  }
371
372  return sites
373}
374
375function toRepoDataAidokuLegacy(iconBase: string, sources: AidokuLegacySource[]): RepoSite[] {
376  const seen = new Set<string>()
377  const sites: RepoSite[] = []
378
379  for (const source of sources) {
380    const lang = normalizeLang(source.lang)
381    const key = `${source.name}::${lang}`
382    if (seen.has(key)) continue
383    seen.add(key)
384    sites.push({ name: source.name, lang, icon: `${iconBase}/icons/${source.icon}`, url: '', rating: ratingFromLevel(source.nsfw ?? 0) })
385  }
386
387  return sites
388}
389
390function toRepoDataHayase(extensions: HayaseExtension[]): RepoSite[] {
391  const seen = new Set<string>()
392  const sites: RepoSite[] = []
393
394  for (const ext of extensions) {
395    const langs = ext.languages?.length ? ext.languages : ['all']
396    for (const rawLang of langs) {
397      const lang = normalizeLang(rawLang)
398      const key = `${ext.name}::${lang}`
399      if (seen.has(key)) continue
400      seen.add(key)
401      sites.push({ name: ext.name, lang, icon: ext.icon ?? '', url: '', rating: 'safe' })
402    }
403  }
404
405  return sites
406}
407
408function toRepoDataLegado(sources: LegadoBookSource[]): RepoSite[] {
409  const seen = new Set<string>()
410  const sites: RepoSite[] = []
411
412  for (const source of sources) {
413    const lang = normalizeLang(source.bookSourceGroup ?? 'all')
414    const key = `${source.bookSourceName}::${lang}`
415    if (seen.has(key)) continue
416    seen.add(key)
417    sites.push({ name: source.bookSourceName, lang, icon: '', url: source.bookSourceUrl, rating: 'safe' })
418  }
419
420  return sites
421}
422
423function toRepoDataMangayomi(sources: MangayomiSource[]): RepoSite[] {
424  const seen = new Set<string>()
425  const sites: RepoSite[] = []
426
427  for (const source of sources) {
428    const lang = normalizeLang(source.lang)
429    const key = `${source.name}::${lang}`
430    if (seen.has(key)) continue
431    seen.add(key)
432    sites.push({ name: source.name, lang, icon: source.iconUrl ?? '', url: source.baseUrl, rating: source.isNsfw ? 'nsfw' : 'safe' })
433  }
434
435  return sites
436}
437
438function toRepoDataIReader(sources: IReaderSource[]): RepoSite[] {
439  const seen = new Set<string>()
440  const sites: RepoSite[] = []
441
442  for (const source of sources) {
443    const lang = normalizeLang(source.lang)
444    const key = `${source.name}::${lang}`
445    if (seen.has(key)) continue
446    seen.add(key)
447    // No confirmed icon path convention in this repo's format — omit rather than guess wrong.
448    sites.push({ name: source.name, lang, icon: '', url: '', rating: source.nsfw ? 'nsfw' : 'safe' })
449  }
450
451  return sites
452}
453
454function toRepoDataSuwatte(iconBase: string, index: SuwatteCatalogIndex): { sites: RepoSite[]; listUrl: string } {
455  const seen = new Set<string>()
456  const sites: RepoSite[] = []
457
458  const listUrl = index.listUrl ?? iconBase
459  const isV6 = index.catalogVersion === undefined
460
461  for (const source of index.sources ?? []) {
462    const langs = source.languages?.length ? source.languages : ['all']
463    const icon = source.thumbnail
464      ? (/^https?:\/\//i.test(source.thumbnail) ? source.thumbnail : `${iconBase}/assets/${source.thumbnail}`)
465      : ''
466    const installUrl = source.path
467      ? (isV6
468          ? `suwatte://runner?url=${listUrl}&runner=${source.path}`
469          : `suwatte://AddSourceFromList?list=${listUrl}&source=${source.path}`)
470      : undefined
471    for (const rawLang of langs) {
472      const lang = normalizeLang(rawLang)
473      const key = `${source.name}::${lang}`
474      if (seen.has(key)) continue
475      seen.add(key)
476      sites.push({ name: source.name, lang, icon, url: source.website ?? '', rating: 'safe', installUrl })
477    }
478  }
479
480  return { sites, listUrl }
481}
482
483function toRepoDataKotatsu(index: KotatsuIndex): RepoSite[] {
484  const seen = new Set<string>()
485  const sites: RepoSite[] = []
486
487  for (const site of index.sites) {
488    const lang = normalizeLang(site.lang)
489    const key = `${site.name}::${lang}::${site.url}`
490    if (seen.has(key)) continue
491    seen.add(key)
492    const rating: Rating = site.contentType.includes('HENTAI') ? 'nsfw' : 'safe'
493    sites.push({ name: site.name, lang, icon: site.icon, url: site.url, rating, contentType: site.contentType, isBroken: site.isBroken || undefined })
494  }
495
496  return sites
497}
498
499function isSoraLibrary(json: unknown): json is SoraLibraryAuthor[] {
500  if (!Array.isArray(json) || json.length === 0) return false
501  const first = json[0] as Record<string, unknown>
502  return typeof first.author === 'string' && typeof first.repo === 'string' && typeof first.types === 'object'
503}
504
505function normalizeSoraLang(language: string | undefined): string {
506  const stripped = (language ?? '').replace(/\s*\([^)]*\)\s*$/, '').trim()
507  if (stripped.toLowerCase().startsWith('multi')) return 'all'
508  return normalizeLang(stripped)
509}
510
511const SORA_TYPE_ORDER = ['anime', 'manga', 'novels', 'other']
512const SORA_TYPE_LABELS: Record<string, string> = {
513  anime: 'Anime',
514  manga: 'Manga',
515  novels: 'Novels',
516  other: 'Other'
517}
518
519function soraModuleInstallUrl(mod: SoraLibraryModule): string | undefined {
520  const explicit = mod.manifestUrl ?? mod.jsonUrl
521  if (explicit) return explicit
522  const script = mod.scriptUrl ?? mod.scriptURL
523  return script?.replace(/\.js$/i, '.json')
524}
525
526function toRepoDataSoraModules(modules: SoraLibraryModule[]): RepoSite[] {
527  const seen = new Set<string>()
528  const sites: RepoSite[] = []
529
530  for (const mod of modules) {
531    const lang = normalizeSoraLang(mod.languageClean ?? mod.language)
532    const installUrl = soraModuleInstallUrl(mod)
533    const key = `${mod.sourceName}::${lang}::${installUrl ?? ''}`
534    if (seen.has(key)) continue
535    seen.add(key)
536    sites.push({
537      name: mod.sourceName,
538      lang,
539      icon: mod.iconUrl ?? mod.iconURL ?? '',
540      url: mod.baseUrl ?? '',
541      rating: 'safe',
542      installUrl: installUrl ? `sora://module?url=${installUrl}` : undefined
543    })
544  }
545
546  sites.sort((a, b) => a.name.localeCompare(b.name))
547  return sites
548}
549
550function groupSoraLibrary(indexUrl: string, authors: SoraLibraryAuthor[]): { authorRepos: SoraAuthorRepo[]; sitesByType: Record<string, RepoData> } {
551  const authorRepos: SoraAuthorRepo[] = []
552  const sitesByType: Record<string, RepoData> = {}
553
554  for (const entry of authors) {
555    const types: SoraTypeGroup[] = []
556    for (const typeKey of SORA_TYPE_ORDER) {
557      const modules = entry.types[typeKey]
558      if (!modules?.length) continue
559      const typeIndexUrl = new URL(`${entry.author}/${typeKey}.json`, indexUrl).toString()
560      sitesByType[typeIndexUrl] = { sites: toRepoDataSoraModules(modules) }
561      types.push({ label: SORA_TYPE_LABELS[typeKey] ?? typeKey, indexUrl: typeIndexUrl })
562    }
563    if (!types.length) continue
564    authorRepos.push({ label: entry.author, repoUrl: entry.repo.replace(/\.git$/, ''), types })
565  }
566
567  authorRepos.sort((a, b) => a.label.localeCompare(b.label))
568  return { authorRepos, sitesByType }
569}
570
571function toRepoDataLNReader(plugins: LNReaderPlugin[]): RepoSite[] {
572  const seen = new Set<string>()
573  const sites: RepoSite[] = []
574
575  for (const plugin of plugins) {
576    const lang = normalizeLang(plugin.lang)
577    const key = `${plugin.name}::${lang}`
578    if (seen.has(key)) continue
579    seen.add(key)
580    sites.push({ name: plugin.name, lang, icon: plugin.iconUrl ?? '', url: plugin.url, rating: 'safe' })
581  }
582
583  return sites
584}
585
586async function toRepoData(indexUrl: string, json: unknown): Promise<RepoData> {
587  const iconBase = indexUrl.slice(0, indexUrl.lastIndexOf('/'))
588  let sites: RepoSite[]
589  let suwatteV6: boolean | undefined
590  let suwatteListUrl: string | undefined
591  if (Array.isArray(json)) {
592    const first = json[0] as Record<string, unknown> | undefined
593    if (first && 'bookSourceUrl' in first) {
594      sites = toRepoDataLegado(json as LegadoBookSource[])
595    } else if (first && 'manifestVersion' in first) {
596      sites = toRepoDataHayase(json as HayaseExtension[])
597    } else if (first && 'iconUrl' in first && 'site' in first) {
598      sites = toRepoDataLNReader(json as LNReaderPlugin[])
599    } else if (isSoraLibrary(json)) {
600      sites = toRepoDataSoraModules(json.flatMap(entry => Object.values(entry.types).flat()))
601    } else if (first && 'sources' in first) {
602      sites = toRepoDataMihon(iconBase, json as MihonExtension[])
603    } else if (first && 'pkg' in first && 'apk' in first) {
604      sites = toRepoDataIReader(json as IReaderSource[])
605    } else if (first && 'iconUrl' in first && 'baseUrl' in first) {
606      sites = toRepoDataMangayomi(json as MangayomiSource[])
607    } else {
608      sites = toRepoDataAidokuLegacy(iconBase, json as AidokuLegacySource[])
609    }
610  } else if (Array.isArray((json as CloudstreamRepo).pluginLists)) {
611    sites = await toRepoDataCloudstream(json as CloudstreamRepo)
612  } else if ((json as AidokuIndex).sources?.length && 'iconURL' in (json as AidokuIndex).sources[0]) {
613    sites = toRepoDataAidoku(iconBase, json as AidokuIndex)
614  } else if ((json as SuwatteCatalogIndex).sources?.length && 'thumbnail' in (json as SuwatteCatalogIndex).sources[0]) {
615    const result = toRepoDataSuwatte(iconBase, json as SuwatteCatalogIndex)
616    sites = result.sites
617    suwatteListUrl = result.listUrl
618    suwatteV6 = (json as SuwatteCatalogIndex).catalogVersion === undefined
619  } else if (Array.isArray((json as KotatsuIndex).sites)) {
620    sites = toRepoDataKotatsu(json as KotatsuIndex)
621  } else {
622    sites = toRepoDataPaperback(iconBase, json as PaperbackIndex)
623  }
624  sites.sort((a, b) => a.name.localeCompare(b.name))
625  return { sites, suwatteV6, suwatteListUrl }
626}
627
628export interface ExtensionRepoData {
629  sites: Record<string, RepoData>
630  soraAuthors: Record<string, SoraAuthorRepo[]>
631}
632
633export declare const data: ExtensionRepoData
634
635export default {
636  watch: ['../**/*.md'],
637  async load(): Promise<ExtensionRepoData> {
638    const urls = collectIndexUrls()
639    const sites: Record<string, RepoData> = {}
640    const soraAuthors: Record<string, SoraAuthorRepo[]> = {}
641    await Promise.all(urls.map(async url => {
642      const json = await fetchIndex(url)
643      sites[url] = await toRepoData(url, json)
644      if (isSoraLibrary(json)) {
645        const grouped = groupSoraLibrary(url, json)
646        soraAuthors[url] = grouped.authorRepos
647        Object.assign(sites, grouped.sitesByType)
648      }
649    }))
650    return { sites, soraAuthors }
651  }
652}