docs/ext/extensionRepos.data.ts

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

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