docs/ext/extensionRepos.data.ts
979 lines · 29993 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
22interface MihonIndexSource {
23 id: string
24 name: string
25 language: string
26 homeUrl: string
27 mirrorUrls?: string[]
28}
29
30interface MihonIndexExtension {
31 name: string
32 packageName: string
33 resources: {
34 apkUrl: string
35 iconUrl: string
36 jarUrl: string
37 }
38 extensionLib: string
39 versionCode: string
40 versionName: string
41 contentWarning: string
42 sources: MihonIndexSource[]
43}
44
45interface MihonIndex {
46 name: string
47 badgeLabel: string
48 signingKey: string
49 contact?: {
50 website?: string
51 discord?: string
52 }
53 extensionList: {
54 extensions: MihonIndexExtension[]
55 }
56}
57
58export interface RepoData {
59 sites: RepoSite[]
60 suwatteV6?: boolean
61 suwatteListUrl?: string
62}
63
64interface MihonSource {
65 name: string
66 lang: string
67 baseUrl: string
68}
69
70interface MihonExtension {
71 pkg: string
72 nsfw?: number
73 sources?: MihonSource[]
74}
75
76interface AidokuSource {
77 name: string
78 iconURL: string
79 languages?: string[]
80 contentRating?: number
81 baseURL: string
82}
83
84interface AidokuIndex {
85 sources: AidokuSource[]
86}
87
88interface AidokuLegacySource {
89 name: string
90 icon: string
91 lang: string
92 nsfw?: number
93}
94
95interface PaperbackSource {
96 id: string
97 name: string
98 icon: string
99 language?: string
100 contentRating?: string
101 websiteBaseURL?: string
102}
103
104interface PaperbackIndex {
105 sources: PaperbackSource[]
106 builtWith?: { toolchain?: string }
107}
108
109interface CloudstreamRepo {
110 name?: string
111 pluginLists: string[]
112}
113
114interface CloudstreamRepoListItem {
115 url: string
116 verified?: boolean
117}
118
119export interface RepoListEntry {
120 label: string
121 indexUrl: string
122 repoUrl?: string
123}
124
125interface CloudstreamPlugin {
126 name: string
127 iconUrl?: string
128 language?: string
129}
130
131interface HayaseExtension {
132 name: string
133 icon?: string
134 languages?: string[]
135}
136
137interface LegadoBookSource {
138 bookSourceName: string
139 bookSourceUrl: string
140 bookSourceGroup?: string
141}
142
143interface LNReaderPlugin {
144 name: string
145 lang: string
146 url: string
147 iconUrl?: string
148}
149
150interface MangayomiSource {
151 name: string
152 lang: string
153 baseUrl: string
154 iconUrl?: string
155 isNsfw?: boolean
156}
157
158interface IReaderSource {
159 pkg: string
160 apk: string
161 name: string
162 lang: string
163 nsfw?: boolean
164}
165
166interface SuwatteCatalogSource {
167 name: string
168 website?: string
169 languages?: string[]
170 thumbnail?: string
171 path?: string
172}
173
174interface SuwatteCatalogIndex {
175 listUrl?: string
176 catalogVersion?: number
177 sources: SuwatteCatalogSource[]
178}
179
180// For kotatsu
181interface KotatsuSite {
182 name: string
183 lang: string
184 url: string
185 icon: string
186 contentType: string
187 isBroken: boolean
188}
189
190interface KotatsuIndex {
191 sites: KotatsuSite[]
192}
193
194interface SoraRepoIndexEntry {
195 slug: string
196 name: string
197 source: string
198 path?: string
199 totalSources?: number
200 error?: string
201}
202
203interface SoraRepoIndex {
204 repos: SoraRepoIndexEntry[]
205}
206
207interface SoraModule {
208 sourceName: string
209 iconUrl?: string
210 iconURL?: string
211 language?: string
212 baseUrl?: string
213 scriptUrl?: string
214 scriptURL?: string
215 wotaku_sourceName?: string
216 wotaku_language?: string[]
217 wotaku_type?: string[]
218 wotaku_streamType?: string[]
219 wotaku_quality?: string[]
220}
221
222export interface SoraAuthorRepo {
223 label: string
224 repoUrl?: string
225 indexUrl: string
226}
227
228interface EchoExtension {
229 id: string
230 type: string
231 name: string
232 subtitle?: string
233 iconUrl?: string
234 url?: string
235 updateUrl: string
236}
237
238export interface EchoAuthorRepo {
239 label: string
240 repoUrl?: string
241 indexUrl: string
242}
243
244const EXT_DIR = dirname(fileURLToPath(import.meta.url))
245const DOCS_DIR = join(EXT_DIR, '..')
246const CACHE_DIR = join(EXT_DIR, '../.vitepress/cache/extension-repos')
247const CACHE_TTL_MS = 6 * 60 * 60 * 1000
248
249function findMarkdownFiles(dir: string): string[] {
250 const files: string[] = []
251 for (const entry of readdirSync(dir, { withFileTypes: true })) {
252 if (entry.isDirectory()) {
253 if (!IGNORED_DIRS.has(entry.name)) files.push(...findMarkdownFiles(join(dir, entry.name)))
254 } else if (entry.name.endsWith('.md')) {
255 files.push(join(dir, entry.name))
256 }
257 }
258 return files
259}
260
261function collectIndexUrls(): string[] {
262 const urls = new Set<string>()
263 const blockRe = /:::\s*extrepo[^\n]*\n([\s\S]*?)\n\s*:::/g
264 const rowRe = /^\s*-\s*(raw|manga|anime|novel|data)\s*:\s*(https?:\/\/\S+)\s*$/i
265 const headingRe = /^\s*==\s+.+$/
266 const buildRe = /^\s*--\s+.+$/
267
268 function flushEntry(plainRaws: string[], variantUrls: string[], buildRaws: string[], dataUrls: string[]): void {
269 for (const url of variantUrls) urls.add(url)
270 for (const url of buildRaws) urls.add(url)
271 for (const url of dataUrls) urls.add(url)
272 if (dataUrls.length === 0) {
273 for (const url of plainRaws) urls.add(url)
274 }
275 }
276
277 for (const file of findMarkdownFiles(DOCS_DIR)) {
278 const src = readFileSync(file, 'utf-8')
279
280 let block: RegExpExecArray | null
281 blockRe.lastIndex = 0
282 while ((block = blockRe.exec(src))) {
283 let plainRaws: string[] = []
284 let variantUrls: string[] = []
285 let buildRaws: string[] = []
286 let dataUrls: string[] = []
287 let inEntry = false
288 let inBuild = false
289
290 for (const line of block[1].split('\n')) {
291 if (headingRe.test(line)) {
292 if (inEntry) flushEntry(plainRaws, variantUrls, buildRaws, dataUrls)
293 plainRaws = []
294 variantUrls = []
295 buildRaws = []
296 dataUrls = []
297 inEntry = true
298 inBuild = false
299 continue
300 }
301 if (buildRe.test(line)) {
302 inBuild = true
303 continue
304 }
305 const row = rowRe.exec(line)
306 if (row && inEntry) {
307 const key = row[1].toLowerCase()
308 const url = row[2].trim()
309 if (key === 'data') dataUrls.push(url)
310 else if (key === 'raw') (inBuild ? buildRaws : plainRaws).push(url)
311 else variantUrls.push(url)
312 }
313 }
314 if (inEntry) flushEntry(plainRaws, variantUrls, buildRaws, dataUrls)
315 }
316 }
317 return [...urls]
318}
319
320function cachePathFor(url: string): string {
321 return join(CACHE_DIR, `${Buffer.from(url).toString('base64url')}.json`)
322}
323
324function collectRepoListUrls(): string[] {
325 const urls = new Set<string>()
326 const blockRe = /:::\s*extrepo\s*\{([^}]*)\}/g
327
328 for (const file of findMarkdownFiles(DOCS_DIR)) {
329 const src = readFileSync(file, 'utf-8')
330
331 let match: RegExpExecArray | null
332 blockRe.lastIndex = 0
333 while ((match = blockRe.exec(src))) {
334 const from = match[1].match(/(?:^|\s)from=(?:"([^"]+)"|'([^']+)'|(\S+))/)
335 if (from) urls.add((from[1] ?? from[2] ?? from[3]).trim())
336 }
337 }
338 return [...urls]
339}
340
341function isCloudstreamRepoList(json: unknown): json is Array<string | CloudstreamRepoListItem> {
342 if (!Array.isArray(json) || json.length === 0) return false
343 return json.every(item => {
344 if (typeof item === 'string') return /^https?:\/\//.test(item)
345 if (item && typeof item === 'object') {
346 const rec = item as Record<string, unknown>
347 // LNReader plugins also carry a `url` field — rule those out.
348 if ('name' in rec || 'lang' in rec || 'baseUrl' in rec || 'baseURL' in rec) return false
349 return typeof rec.url === 'string' && /^https?:\/\//.test(rec.url)
350 }
351 return false
352 })
353}
354
355function inferRepoUrl(rawUrl: string): string | undefined {
356 try {
357 const u = new URL(rawUrl)
358 const parts = u.pathname.split('/').filter(Boolean)
359 if (u.hostname === 'raw.githubusercontent.com' && parts.length >= 2) {
360 return `https://github.com/${parts[0]}/${parts[1]}`
361 }
362 const dashRaw = u.pathname.indexOf('/-/raw/')
363 if (dashRaw > 0) return `${u.origin}${u.pathname.slice(0, dashRaw)}`
364 const rawSeg = parts.indexOf('raw')
365 if (rawSeg > 1) return `${u.origin}/${parts.slice(0, rawSeg).join('/')}`
366 } catch {
367 return undefined
368 }
369 return undefined
370}
371
372function inferLabel(rawUrl: string): string {
373 const repoUrl = inferRepoUrl(rawUrl)
374 if (repoUrl) {
375 try {
376 const parts = new URL(repoUrl).pathname.split('/').filter(Boolean)
377 if (parts.length >= 2) return `${parts[parts.length - 2]}/${parts[parts.length - 1]}`
378 if (parts.length === 1) return decodeURIComponent(parts[0])
379 } catch {
380 // fall through to raw-URL fallback below
381 }
382 }
383 try {
384 const parts = new URL(rawUrl).pathname.split('/').filter(Boolean)
385 return decodeURIComponent(parts[parts.length - 2] ?? parts[parts.length - 1] ?? rawUrl)
386 } catch {
387 return rawUrl
388 }
389}
390
391function repoListLabel(indexUrl: string, repoJson: unknown): string {
392 if (repoJson && typeof repoJson === 'object' && !Array.isArray(repoJson)) {
393 const name = (repoJson as { name?: unknown }).name
394 if (typeof name === 'string' && name.trim() !== '') return name.trim()
395 }
396 return inferLabel(indexUrl)
397}
398
399async function fetchIndex(url: string): Promise<unknown> {
400 const cachePath = cachePathFor(url)
401 if (existsSync(cachePath) && Date.now() - statSync(cachePath).mtimeMs < CACHE_TTL_MS) {
402 return JSON.parse(readFileSync(cachePath, 'utf-8'))
403 }
404
405 try {
406 const res = await fetch(url)
407 if (!res.ok) throw new Error(`${res.status} ${res.statusText}`)
408 const json = await res.json()
409 mkdirSync(CACHE_DIR, { recursive: true })
410 writeFileSync(cachePath, JSON.stringify(json))
411 return json
412 } catch (err) {
413 if (existsSync(cachePath)) return JSON.parse(readFileSync(cachePath, 'utf-8'))
414 console.warn(`[extrepo] failed to fetch ${url}: ${(err as Error).message}`)
415 return []
416 }
417}
418
419function ratingFromLevel(level: number): Rating {
420 if (level >= 2) return 'nsfw'
421 if (level >= 1) return 'suggestive'
422 return 'safe'
423}
424
425const LANG_ALIASES: Record<string, string> = {
426 jp: 'ja',
427 english: 'en',
428 'bahasa indonesia': 'id',
429 español: 'es',
430 français: 'fr',
431 polski: 'pl',
432 português: 'pt',
433 'tiếng việt': 'vi',
434 türkçe: 'tr',
435 русский: 'ru',
436 українська: 'uk',
437 ไทย: 'th',
438 العربية: 'ar',
439 chinese: 'zh',
440 japanese: 'ja',
441 korean: 'ko',
442 french: 'fr',
443 german: 'de',
444 greek: 'el',
445 indonesian: 'id',
446 italian: 'it',
447 spanish: 'es',
448 turkish: 'tr',
449 polish: 'pl',
450 russian: 'ru',
451 portuguese: 'pt',
452 arabic: 'ar',
453 tamil: 'ta',
454 ukrainian: 'uk',
455 vietnamese: 'vi',
456 thai: 'th',
457 hindi: 'hi',
458 malay: 'ms',
459 serbian: 'sr'
460}
461
462const LANG_SUBSTRING_ALIASES: [RegExp, string][] = [
463 [/日语原版/, 'ja'],
464 [/中文|汉语|漢語|轻小说/, 'zh'],
465 [/日本語/, 'ja'],
466 [/한국어|조선말/, 'ko']
467]
468
469function normalizeLang(lang: string): string {
470 // Strip bidi control marks (e.g. U+200E/U+200F) some indices prepend to lang names.
471 const cleaned = lang.replace(/[]/g, '').trim()
472 if (cleaned === '') return 'all'
473 const exact = LANG_ALIASES[cleaned.toLowerCase()]
474 if (exact) return exact
475 for (const [re, code] of LANG_SUBSTRING_ALIASES) {
476 if (re.test(cleaned)) return code
477 }
478 const key = cleaned.toLowerCase()
479 return key === 'multi' ? 'all' : key
480}
481
482function toRepoDataMihon(iconBase: string, extensions: MihonExtension[]): RepoSite[] {
483 const seen = new Set<string>()
484 const sites: RepoSite[] = []
485
486 for (const ext of extensions) {
487 const icon = `${iconBase}/icon/${ext.pkg}.png`
488 for (const source of ext.sources ?? []) {
489 const key = `${source.name}::${source.lang}::${source.baseUrl}`
490 if (seen.has(key)) continue
491 seen.add(key)
492 sites.push({ name: source.name, lang: source.lang, icon, url: source.baseUrl, rating: ext.nsfw === 1 ? 'nsfw' : 'safe' })
493 }
494 }
495
496 return sites
497}
498
499function toRepoDataAidoku(iconBase: string, index: AidokuIndex): RepoSite[] {
500 const seen = new Set<string>()
501 const sites: RepoSite[] = []
502
503 for (const source of index.sources ?? []) {
504 const icon = `${iconBase}/${source.iconURL}`
505 const rating = ratingFromLevel(source.contentRating ?? 0)
506 const langs = source.languages?.length ? source.languages : ['all']
507 for (const rawLang of langs) {
508 const lang = normalizeLang(rawLang)
509 const key = `${source.name}::${lang}::${source.baseURL}`
510 if (seen.has(key)) continue
511 seen.add(key)
512 sites.push({ name: source.name, lang, icon, url: source.baseURL, rating })
513 }
514 }
515
516 return sites
517}
518
519function toRepoDataPaperback(iconBase: string, index: PaperbackIndex): RepoSite[] {
520 const seen = new Set<string>()
521 const sites: RepoSite[] = []
522 // Legacy 0.8.x toolchain builds serve icons under `<id>/includes/`
523 const iconDir = index.builtWith?.toolchain?.startsWith('0.8') ? 'includes' : 'static'
524
525 for (const source of index.sources ?? []) {
526 const lang = normalizeLang(source.language ?? 'all')
527 const key = `${source.id}::${lang}`
528 if (seen.has(key)) continue
529 seen.add(key)
530 const icon = `${iconBase}/${source.id}/${iconDir}/${source.icon}`
531 const rating: Rating = source.contentRating === 'ADULT' ? 'nsfw' : source.contentRating === 'MATURE' ? 'suggestive' : 'safe'
532 sites.push({ name: source.name, lang, icon, url: source.websiteBaseURL ?? '', rating })
533 }
534
535 return sites
536}
537
538function normalizeGoogleFaviconUrl(url: string): string {
539 return url.replace('%size%', '64')
540}
541
542async function toRepoDataCloudstream(repo: CloudstreamRepo): Promise<RepoSite[]> {
543 const seen = new Set<string>()
544 const sites: RepoSite[] = []
545
546 const lists = await Promise.all(repo.pluginLists.map(url => fetchIndex(url)))
547 for (const list of lists) {
548 if (!Array.isArray(list)) continue
549 for (const plugin of list as CloudstreamPlugin[]) {
550 if (seen.has(plugin.name)) continue
551 seen.add(plugin.name)
552 const lang = normalizeLang(plugin.language ?? 'all')
553 const icon = plugin.iconUrl ? normalizeGoogleFaviconUrl(plugin.iconUrl) : ''
554 sites.push({ name: plugin.name, lang, icon, url: '', rating: 'safe' })
555 }
556 }
557
558 return sites
559}
560
561function toRepoDataAidokuLegacy(iconBase: string, sources: AidokuLegacySource[]): RepoSite[] {
562 const seen = new Set<string>()
563 const sites: RepoSite[] = []
564
565 for (const source of sources) {
566 const lang = normalizeLang(source.lang)
567 const key = `${source.name}::${lang}`
568 if (seen.has(key)) continue
569 seen.add(key)
570 sites.push({ name: source.name, lang, icon: `${iconBase}/icons/${source.icon}`, url: '', rating: ratingFromLevel(source.nsfw ?? 0) })
571 }
572
573 return sites
574}
575
576function toRepoDataHayase(extensions: HayaseExtension[]): RepoSite[] {
577 const seen = new Set<string>()
578 const sites: RepoSite[] = []
579
580 for (const ext of extensions) {
581 const langs = ext.languages?.length ? ext.languages : ['all']
582 for (const rawLang of langs) {
583 const lang = normalizeLang(rawLang)
584 const key = `${ext.name}::${lang}`
585 if (seen.has(key)) continue
586 seen.add(key)
587 sites.push({ name: ext.name, lang, icon: ext.icon ?? '', url: '', rating: 'safe' })
588 }
589 }
590
591 return sites
592}
593
594function toRepoDataLegado(sources: LegadoBookSource[]): RepoSite[] {
595 const seen = new Set<string>()
596 const sites: RepoSite[] = []
597
598 for (const source of sources) {
599 const lang = normalizeLang(source.bookSourceGroup ?? 'all')
600 const key = `${source.bookSourceName}::${lang}`
601 if (seen.has(key)) continue
602 seen.add(key)
603 sites.push({ name: source.bookSourceName, lang, icon: '', url: source.bookSourceUrl, rating: 'safe' })
604 }
605
606 return sites
607}
608
609function toRepoDataMangayomi(sources: MangayomiSource[]): RepoSite[] {
610 const seen = new Set<string>()
611 const sites: RepoSite[] = []
612
613 for (const source of sources) {
614 const lang = normalizeLang(source.lang)
615 const key = `${source.name}::${lang}`
616 if (seen.has(key)) continue
617 seen.add(key)
618 sites.push({ name: source.name, lang, icon: source.iconUrl ?? '', url: source.baseUrl, rating: source.isNsfw ? 'nsfw' : 'safe' })
619 }
620
621 return sites
622}
623
624function toRepoDataIReader(sources: IReaderSource[]): RepoSite[] {
625 const seen = new Set<string>()
626 const sites: RepoSite[] = []
627
628 for (const source of sources) {
629 const lang = normalizeLang(source.lang)
630 const key = `${source.name}::${lang}`
631 if (seen.has(key)) continue
632 seen.add(key)
633 // No confirmed icon path convention in this repo's format — omit rather than guess wrong.
634 sites.push({ name: source.name, lang, icon: '', url: '', rating: source.nsfw ? 'nsfw' : 'safe' })
635 }
636
637 return sites
638}
639
640function toRepoDataSuwatte(iconBase: string, index: SuwatteCatalogIndex): { sites: RepoSite[]; listUrl: string } {
641 const seen = new Set<string>()
642 const sites: RepoSite[] = []
643
644 const listUrl = index.listUrl ?? iconBase
645 const isV6 = index.catalogVersion === undefined
646
647 for (const source of index.sources ?? []) {
648 const langs = source.languages?.length ? source.languages : ['all']
649 const icon = source.thumbnail
650 ? (/^https?:\/\//i.test(source.thumbnail) ? source.thumbnail : `${iconBase}/assets/${source.thumbnail}`)
651 : ''
652 const installUrl = source.path
653 ? (isV6
654 ? `suwatte://runner?url=${listUrl}&runner=${source.path}`
655 : `suwatte://AddSourceFromList?list=${listUrl}&source=${source.path}`)
656 : undefined
657 for (const rawLang of langs) {
658 const lang = normalizeLang(rawLang)
659 const key = `${source.name}::${lang}`
660 if (seen.has(key)) continue
661 seen.add(key)
662 sites.push({ name: source.name, lang, icon, url: source.website ?? '', rating: 'safe', installUrl })
663 }
664 }
665
666 return { sites, listUrl }
667}
668
669function toRepoDataKotatsu(index: KotatsuIndex): RepoSite[] {
670 const seen = new Set<string>()
671 const sites: RepoSite[] = []
672
673 for (const site of index.sites) {
674 const lang = normalizeLang(site.lang)
675 const key = `${site.name}::${lang}::${site.url}`
676 if (seen.has(key)) continue
677 seen.add(key)
678 const rating: Rating = site.contentType.includes('HENTAI') ? 'nsfw' : 'safe'
679 sites.push({ name: site.name, lang, icon: site.icon, url: site.url, rating, contentType: site.contentType, isBroken: site.isBroken || undefined })
680 }
681
682 return sites
683}
684
685function isSoraRepoIndex(json: unknown): json is SoraRepoIndex {
686 return !!json && typeof json === 'object' && Array.isArray((json as SoraRepoIndex).repos)
687}
688
689function normalizeSoraLang(language: string | undefined): string {
690 const stripped = (language ?? '').replace(/\s*\([^)]*\)\s*$/, '').trim()
691 if (stripped.toLowerCase().startsWith('multi')) return 'all'
692 return normalizeLang(stripped)
693}
694
695function toRepoDataSoraModules(modules: SoraModule[]): RepoSite[] {
696 const seen = new Set<string>()
697 const sites: RepoSite[] = []
698
699 for (const mod of modules) {
700 const name = mod.wotaku_sourceName ?? mod.sourceName
701 const langs = mod.wotaku_language?.length ? mod.wotaku_language : [mod.language]
702 const scriptUrl = mod.scriptUrl ?? mod.scriptURL
703 const installUrl = scriptUrl?.replace(/\.js$/i, '.json')
704 for (const rawLang of langs) {
705 const lang = normalizeSoraLang(rawLang)
706 const key = `${name}::${lang}::${installUrl ?? ''}`
707 if (seen.has(key)) continue
708 seen.add(key)
709 sites.push({
710 name,
711 lang,
712 icon: mod.iconUrl ?? mod.iconURL ?? '',
713 url: mod.baseUrl ?? '',
714 rating: 'safe',
715 contentType: mod.wotaku_type?.[0],
716 streamType: mod.wotaku_streamType?.[0],
717 quality: mod.wotaku_quality?.[0],
718 installUrl: installUrl ? `sora://module?url=${installUrl}` : undefined
719 })
720 }
721 }
722
723 sites.sort((a, b) => a.name.localeCompare(b.name))
724 return sites
725}
726
727async function loadSoraRepoIndex(indexUrl: string, index: SoraRepoIndex): Promise<{ sites: RepoSite[]; authorRepos: SoraAuthorRepo[]; sitesByAuthor: Record<string, RepoData> }> {
728 const seen = new Set<string>()
729 const sites: RepoSite[] = []
730 const authorRepos: SoraAuthorRepo[] = []
731 const sitesByAuthor: Record<string, RepoData> = {}
732
733 const entries = index.repos.filter(repo => repo.path && !repo.error)
734 const fileUrls = entries.map(repo => new URL(repo.path!, indexUrl).toString())
735 const moduleLists = await Promise.all(fileUrls.map(url => fetchIndex(url)))
736
737 entries.forEach((repo, i) => {
738 const modules = moduleLists[i]
739 const authorSites = Array.isArray(modules) ? toRepoDataSoraModules(modules as SoraModule[]) : []
740 const fileUrl = fileUrls[i]
741 sitesByAuthor[fileUrl] = { sites: authorSites }
742 authorRepos.push({ label: repo.name, repoUrl: repo.source?.replace(/\.git$/, ''), indexUrl: fileUrl })
743 for (const site of authorSites) {
744 const key = `${site.name}::${site.lang}::${site.installUrl ?? ''}`
745 if (seen.has(key)) continue
746 seen.add(key)
747 sites.push(site)
748 }
749 })
750
751 authorRepos.sort((a, b) => a.label.localeCompare(b.label))
752 sites.sort((a, b) => a.name.localeCompare(b.name))
753 return { sites, authorRepos, sitesByAuthor }
754}
755
756function isEchoExtensionList(json: unknown): json is EchoExtension[] {
757 if (!Array.isArray(json) || json.length === 0) return false
758 const first = json[0] as Record<string, unknown>
759 return typeof first.updateUrl === 'string' && typeof first.subtitle === 'string' && !('lang' in first) && !('baseUrl' in first)
760}
761
762function parseEchoRepo(updateUrl: string): { host: string; owner: string; repo: string; repoUrl: string; ownerUrl: string } | undefined {
763 const githubMatch = updateUrl.match(/^https:\/\/api\.github\.com\/repos\/([^/]+)\/([^/]+)\/releases$/)
764 if (githubMatch) {
765 const [, owner, repo] = githubMatch
766 return { host: 'github.com', owner, repo, repoUrl: `https://github.com/${owner}/${repo}`, ownerUrl: `https://github.com/${owner}` }
767 }
768
769 const gitlabMatch = updateUrl.match(/^https:\/\/(gitlab\.com)\/api\/v4\/projects\/([^/]+)\/releases\b/)
770 if (gitlabMatch) {
771 const [, host, encodedPath] = gitlabMatch
772 const path = decodeURIComponent(encodedPath)
773 const owner = path.slice(0, path.lastIndexOf('/'))
774 const repo = path.slice(path.lastIndexOf('/') + 1)
775 if (!owner || !repo) return undefined
776 return { host, owner, repo, repoUrl: `https://${host}/${path}`, ownerUrl: `https://${host}/${owner}` }
777 }
778
779 return undefined
780}
781
782function toRepoDataEchoExtensions(extensions: EchoExtension[]): RepoSite[] {
783 const seen = new Set<string>()
784 const sites: RepoSite[] = []
785
786 for (const ext of extensions) {
787 const key = `${ext.id}::${ext.updateUrl}`
788 if (seen.has(key)) continue
789 seen.add(key)
790 const repo = parseEchoRepo(ext.updateUrl)
791 sites.push({
792 name: ext.name,
793 lang: 'all',
794 icon: ext.iconUrl ?? '',
795 url: ext.url ?? repo?.repoUrl ?? '',
796 rating: 'safe',
797 contentType: ext.type,
798 installUrl: repo?.repoUrl
799 })
800 }
801
802 sites.sort((a, b) => a.name.localeCompare(b.name))
803 return sites
804}
805
806function loadEchoExtensionList(indexUrl: string, extensions: EchoExtension[]): { sites: RepoSite[]; authorRepos: EchoAuthorRepo[]; sitesByAuthor: Record<string, RepoData> } {
807 const byAuthor = new Map<string, { label: string; ownerUrl?: string; exts: EchoExtension[] }>()
808 for (const ext of extensions) {
809 const repo = parseEchoRepo(ext.updateUrl)
810 const key = repo ? `${repo.host}:${repo.owner}` : 'Unknown'
811 const bucket = byAuthor.get(key)
812 if (bucket) bucket.exts.push(ext)
813 else byAuthor.set(key, { label: repo?.owner ?? 'Unknown', ownerUrl: repo?.ownerUrl, exts: [ext] })
814 }
815
816 const authorRepos: EchoAuthorRepo[] = []
817 const sitesByAuthor: Record<string, RepoData> = {}
818 for (const [key, { label, ownerUrl, exts }] of byAuthor) {
819 const authorIndexUrl = `${indexUrl}#${key}`
820 sitesByAuthor[authorIndexUrl] = { sites: toRepoDataEchoExtensions(exts) }
821 authorRepos.push({ label, repoUrl: ownerUrl, indexUrl: authorIndexUrl })
822 }
823
824 authorRepos.sort((a, b) => a.label.localeCompare(b.label))
825 return { sites: toRepoDataEchoExtensions(extensions), authorRepos, sitesByAuthor }
826}
827
828function toRepoDataLNReader(plugins: LNReaderPlugin[]): RepoSite[] {
829 const seen = new Set<string>()
830 const sites: RepoSite[] = []
831
832 for (const plugin of plugins) {
833 const lang = normalizeLang(plugin.lang)
834 const key = `${plugin.name}::${lang}`
835 if (seen.has(key)) continue
836 seen.add(key)
837 sites.push({ name: plugin.name, lang, icon: plugin.iconUrl ?? '', url: plugin.url, rating: 'safe' })
838 }
839
840 return sites
841}
842
843const CONTENT_WARNING_RATING: Record<string, Rating> = {
844 CONTENT_WARNING_NSFW: 'nsfw',
845 CONTENT_WARNING_MIXED: 'suggestive',
846 CONTENT_WARNING_SAFE: 'safe'
847}
848
849function toRepoDataMihonNew(index: MihonIndex): RepoSite[] {
850 const seen = new Set<string>()
851 const sites: RepoSite[] = []
852
853 for (const ext of index.extensionList.extensions) {
854 const icon = ext.resources.iconUrl
855 const rating = CONTENT_WARNING_RATING[ext.contentWarning] ?? 'safe'
856
857 for (const source of ext.sources) {
858 const key = `${source.name}::${source.language}::${source.homeUrl}`
859 if (seen.has(key)) continue
860 seen.add(key)
861 sites.push({ name: source.name, lang: source.language, icon, url: source.homeUrl, rating })
862 }
863 }
864
865 sites.sort((a, b) => a.name.localeCompare(b.name))
866 return sites
867}
868
869async function toRepoData(indexUrl: string, json: unknown): Promise<RepoData> {
870 const iconBase = indexUrl.slice(0, indexUrl.lastIndexOf('/'))
871 let sites: RepoSite[]
872 let suwatteV6: boolean | undefined
873 let suwatteListUrl: string | undefined
874
875 if (
876 json && typeof json === 'object' && !Array.isArray(json)
877 && 'extensionList' in (json as Record<string, unknown>)
878 ) {
879 sites = toRepoDataMihonNew(json as MihonIndex)
880 return { sites }
881 }
882
883 if (Array.isArray(json)) {
884 const first = json[0] as Record<string, unknown> | undefined
885 if (first && 'bookSourceUrl' in first) {
886 sites = toRepoDataLegado(json as LegadoBookSource[])
887 } else if (first && 'manifestVersion' in first) {
888 sites = toRepoDataHayase(json as HayaseExtension[])
889 } else if (first && 'iconUrl' in first && 'site' in first) {
890 sites = toRepoDataLNReader(json as LNReaderPlugin[])
891 } else if (first && 'sources' in first) {
892 sites = toRepoDataMihon(iconBase, json as MihonExtension[])
893 } else if (first && 'pkg' in first && 'apk' in first) {
894 sites = toRepoDataIReader(json as IReaderSource[])
895 } else if (first && 'iconUrl' in first && 'baseUrl' in first) {
896 sites = toRepoDataMangayomi(json as MangayomiSource[])
897 } else {
898 sites = toRepoDataAidokuLegacy(iconBase, json as AidokuLegacySource[])
899 }
900 } else if (Array.isArray((json as CloudstreamRepo).pluginLists)) {
901 sites = await toRepoDataCloudstream(json as CloudstreamRepo)
902 } else if ((json as AidokuIndex).sources?.length && 'iconURL' in (json as AidokuIndex).sources[0]) {
903 sites = toRepoDataAidoku(iconBase, json as AidokuIndex)
904 } else if ((json as SuwatteCatalogIndex).sources?.length && 'thumbnail' in (json as SuwatteCatalogIndex).sources[0]) {
905 const result = toRepoDataSuwatte(iconBase, json as SuwatteCatalogIndex)
906 sites = result.sites
907 suwatteListUrl = result.listUrl
908 suwatteV6 = (json as SuwatteCatalogIndex).catalogVersion === undefined
909 } else if (Array.isArray((json as KotatsuIndex).sites)) {
910 sites = toRepoDataKotatsu(json as KotatsuIndex)
911 } else {
912 sites = toRepoDataPaperback(iconBase, json as PaperbackIndex)
913 }
914 sites.sort((a, b) => a.name.localeCompare(b.name))
915 return { sites, suwatteV6, suwatteListUrl }
916}
917
918export interface ExtensionRepoData {
919 sites: Record<string, RepoData>
920 soraAuthors: Record<string, SoraAuthorRepo[]>
921 echoAuthors: Record<string, EchoAuthorRepo[]>
922 repoLists: Record<string, RepoListEntry[]>
923}
924
925export declare const data: ExtensionRepoData
926
927export default {
928 watch: ['../**/*.md'],
929 async load(): Promise<ExtensionRepoData> {
930 const urls = collectIndexUrls()
931 const listUrls = collectRepoListUrls()
932 const listUrlSet = new Set(listUrls)
933 const sites: Record<string, RepoData> = {}
934 const soraAuthors: Record<string, SoraAuthorRepo[]> = {}
935 const echoAuthors: Record<string, EchoAuthorRepo[]> = {}
936 const repoLists: Record<string, RepoListEntry[]> = {}
937 await Promise.all(listUrls.map(async listUrl => {
938 const json = await fetchIndex(listUrl)
939 if (!isCloudstreamRepoList(json)) {
940 repoLists[listUrl] = []
941 return
942 }
943 const indexUrls = [...new Set(json.map(item => typeof item === 'string' ? item : item.url))]
944 const repoJsons = await Promise.all(indexUrls.map(url => fetchIndex(url)))
945 const entries: RepoListEntry[] = indexUrls.map((indexUrl, i) => ({
946 label: repoListLabel(indexUrl, repoJsons[i]),
947 indexUrl,
948 repoUrl: inferRepoUrl(indexUrl)
949 }))
950 entries.sort((a, b) => a.label.localeCompare(b.label))
951 repoLists[listUrl] = entries
952 await Promise.all(indexUrls.map(async (indexUrl, i) => {
953 if (indexUrl in sites) return
954 sites[indexUrl] = await toRepoData(indexUrl, repoJsons[i])
955 }))
956 }))
957 await Promise.all(urls.map(async url => {
958 if (listUrlSet.has(url)) return
959 if (url in sites) return
960 const json = await fetchIndex(url)
961 if (isSoraRepoIndex(json)) {
962 const result = await loadSoraRepoIndex(url, json)
963 sites[url] = { sites: result.sites }
964 soraAuthors[url] = result.authorRepos
965 Object.assign(sites, result.sitesByAuthor)
966 return
967 }
968 if (isEchoExtensionList(json)) {
969 const result = loadEchoExtensionList(url, json)
970 sites[url] = { sites: result.sites }
971 echoAuthors[url] = result.authorRepos
972 Object.assign(sites, result.sitesByAuthor)
973 return
974 }
975 sites[url] = await toRepoData(url, json)
976 }))
977 return { sites, soraAuthors, echoAuthors, repoLists }
978 }
979}