Commit 673349fe48

673349fe48327c2b5133927d27aa125e257028f7

parent: a34307dd27

Unsigned

Duck <57977673+woducku@users.noreply.github.com> · 2026-09-26 05:40 UTC

init

Layout: unified · split

docs/.vitepress/configs/markdown/index.ts +25
@@ -14,6 +14,7 @@ import { imgLazyload } from '@mdit/plugin-img-lazyload'
14import { imgSize } from '@mdit/plugin-img-size' 14import { imgSize } from '@mdit/plugin-img-size'
15import MdReg from 'markdown-it-regexp' 15import MdReg from 'markdown-it-regexp'
16import type { MarkdownRenderer } from 'vitepress' 16import type { MarkdownRenderer } from 'vitepress'
17import { getMirror } from '../../utils/mirrors'
17import { 18import {
18 getCollapsibleHeadingAnchor, 19 getCollapsibleHeadingAnchor,
19 getTabAnchor, 20 getTabAnchor,
@@ -48,6 +49,7 @@ export function configureMarkdown(md: MarkdownRenderer) {
48 aotolabel: true 49 aotolabel: true
49 }) 50 })
50 md.use(attrs) 51 md.use(attrs)
52 renderMirrorTooltip(md)
51 renderTooltip(md) 53 renderTooltip(md)
52 renderInlineTooltip(md) 54 renderInlineTooltip(md)
53 md.use(markdownSteps) 55 md.use(markdownSteps)
@@ -71,6 +73,29 @@ function renderInlineTooltip(md: MarkdownRenderer) {
71 ) 73 )
72} 74}
73 75
76function renderMirrorTooltip(md: MarkdownRenderer) {
77 md.use(
78 MdReg(/==m:(.+?)==/, ([, cont]: string[]) => {
79 const id = cont.trim()
80
81 if (/^https?:\/\/\S+$/i.test(id)) {
82 const safeUrl = id.replace(/"/g, '&quot;')
83 return `<a href="${safeUrl}" target="_blank" rel="noopener noreferrer"><span class="icon-tip" data-tip="Mirrors" tabindex="-1"><span class="i-material-symbols-directions-alt"></span></span></a>`
84 }
85
86 const item = getMirror(id)
87 if (!item) return `No mirror found for ${id}`
88
89 const title = (item.title || item.id).replace(/"/g, '&quot;')
90 const src = (item.src || '').replace(/"/g, '&quot;')
91 const note = (item.note || '').replace(/"/g, '&quot;')
92 const mirrorsAttr = JSON.stringify(item.mirrors).replace(/'/g, '&#39;')
93
94 return `<MirrorTooltip id="${id}" title="${title}" src="${src}" note="${note}" note-type="${item.noteType}" mirrors='${mirrorsAttr}' />`
95 })
96 )
97}
98
74function renderTooltip(md: MarkdownRenderer) { 99function renderTooltip(md: MarkdownRenderer) {
75 md.use( 100 md.use(
76 MdReg(/==(.+?)==/, ([, cont]: string[]) => { 101 MdReg(/==(.+?)==/, ([, cont]: string[]) => {
docs/.vitepress/plugins/urlSearchPlugin.ts +83 −2
@@ -1,4 +1,5 @@
1import { writeFileSync } from 'node:fs' 1import matter from 'gray-matter'
2import { existsSync, readFileSync, writeFileSync } from 'node:fs'
2import { join } from 'node:path' 3import { join } from 'node:path'
3import { renderEmojiShortcodes } from '../configs/markdown/emoji' 4import { renderEmojiShortcodes } from '../configs/markdown/emoji'
4import { 5import {
@@ -55,6 +56,70 @@ function extractSearchMetadataFromMarkdown(
55 let currentAnchor = '' 56 let currentAnchor = ''
56 let extrepoEntryName: string | null = null 57 let extrepoEntryName: string | null = null
57 58
59 const mirrorCache = new Map<
60 string,
61 { src: string; mirrors: string[]; title: string } | null
62 >()
63
64 const getMirrorUrls = (id: string) => {
65 if (mirrorCache.has(id)) return mirrorCache.get(id)
66 // Direct URL form: ==m:https://example.com/== (no mirror file needed)
67 if (/^https?:\/\/\S+$/i.test(id)) {
68 let title = id
69 try {
70 title = new URL(id).hostname.replace(/^www\./i, '')
71 } catch {
72 /* keep raw */
73 }
74 const entry = { src: id, mirrors: [] as string[], title }
75 mirrorCache.set(id, entry)
76 return entry
77 }
78 try {
79 const filePath = join(
80 process.cwd(),
81 'docs/.vitepress/mirrors',
82 `${id}.md`
83 )
84 if (!existsSync(filePath)) {
85 mirrorCache.set(id, null)
86 return null
87 }
88 const fileContent = readFileSync(filePath, 'utf-8')
89 const { data, content } = matter(fileContent)
90 const src = typeof data.src === 'string' ? data.src.trim() : ''
91 const title = typeof data.title === 'string' && data.title.trim()
92 ? data.title.trim()
93 : id
94 const urls: string[] = []
95 const seen = new Set<string>()
96 for (const m of content.matchAll(/https?:\/\/[^\s<>"')\]]+/g)) {
97 const url = m[0].replace(/[.,;:!?]+$/, '')
98 if (!seen.has(url) && url !== src) {
99 seen.add(url)
100 urls.push(url)
101 }
102 }
103 const entry = { src, mirrors: urls, title }
104 mirrorCache.set(id, entry)
105 return entry
106 } catch {
107 mirrorCache.set(id, null)
108 return null
109 }
110 }
111
112 const getMirrorMainLabel = (line: string, fallback: string) => {
113 const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g
114 let m: RegExpExecArray | null
115 while ((m = linkRE.exec(line)) !== null) {
116 const label = m[1].trim()
117 if (!label || /^:.*:$/.test(label)) continue
118 return renderEmojiShortcodes(label)
119 }
120 return fallback
121 }
122
58 const body = src.startsWith('---') 123 const body = src.startsWith('---')
59 ? src.replace(/^---[\s\S]*?---\n?/, '') 124 ? src.replace(/^---[\s\S]*?---\n?/, '')
60 : src 125 : src
@@ -143,7 +208,9 @@ function extractSearchMetadataFromMarkdown(
143 } 208 }
144 } 209 }
145 210
146 if (containerStack.includes('extrepo') && !containerStack.includes('tabs')) { 211 if (
212 containerStack.includes('extrepo') && !containerStack.includes('tabs')
213 ) {
147 const extrepoHeadingMatch = line.match(/^\s*==\s+(.+)$/) 214 const extrepoHeadingMatch = line.match(/^\s*==\s+(.+)$/)
148 if (extrepoHeadingMatch) { 215 if (extrepoHeadingMatch) {
149 extrepoEntryName = extrepoHeadingMatch[1].trim() 216 extrepoEntryName = extrepoHeadingMatch[1].trim()
@@ -234,6 +301,20 @@ function extractSearchMetadataFromMarkdown(
234 const href = m[1].trim() 301 const href = m[1].trim()
235 pushLink(href, href) 302 pushLink(href, href)
236 } 303 }
304
305 const mirrorRE = /==m:(.+?)==/g
306 let pm: RegExpExecArray | null
307 while ((pm = mirrorRE.exec(line)) !== null) {
308 const id = pm[1].trim()
309 if (!id) continue
310 const mirror = getMirrorUrls(id)
311 if (!mirror) continue
312 const label = getMirrorMainLabel(line, mirror.title)
313 for (const href of [mirror.src, ...mirror.mirrors]) {
314 if (!href) continue
315 pushLink(href.trim(), label)
316 }
317 }
237 } 318 }
238 319
239 return { links, tabTargets: [...tabTargets.values()] } 320 return { links, tabTargets: [...tabTargets.values()] }
docs/.vitepress/theme/components/MirrorTooltip.vue added +480
@@ -0,0 +1,480 @@
1<!--
2 All Rights Reserved
3
4 Copyright (c) 2025 taskylizard
5
6 All rights reserved. This code and its associated files may not be copied, modified, distributed, sublicensed, or used in any form, in whole or in part, without prior written permission from the copyright holder.
7-->
8<script setup lang="ts">
9import { computed, nextTick, ref, watch } from 'vue'
10import { resolveFaviconUrl, useFavicons } from '../composables/useFavicons'
11
12const props = withDefaults(
13 defineProps<{
14 id?: string
15 title?: string
16 src?: string
17 note?: string
18 noteType?: string
19 mirrors?: string | string[]
20 }>(),
21 {
22 id: '',
23 title: 'Mirrors',
24 src: '',
25 note: '',
26 noteType: 'warning',
27 mirrors: () => []
28 }
29)
30
31const NOTE_TYPES = ['info', 'tip', 'warning', 'danger'] as const
32
33const noteClass = computed(() =>
34 `mirror-note--${NOTE_TYPES.includes(props.noteType as typeof NOTE_TYPES[number]) ? props.noteType : 'warning'}`
35)
36
37/** Minimal `[text](url)` support for notes (in-wiki + outbound). */
38function renderNoteLinks(text: string): string {
39 const escaped = text
40 .replace(/&/g, '&amp;')
41 .replace(/</g, '&lt;')
42 .replace(/>/g, '&gt;')
43 return escaped.replace(
44 /\[([^\]]+)\]\(([^)\s]+)\)/g,
45 (_m, t: string, u: string) => {
46 const safeUrl = u.replace(/"/g, '&quot;')
47 const safeText = t.replace(/"/g, '&quot;')
48 const attrs = /^https?:\/\//i.test(u)
49 ? ` href="${safeUrl}" target="_blank" rel="noopener noreferrer"`
50 : ` href="${safeUrl}"`
51 return `<a${attrs}>${safeText}</a>`
52 }
53 )
54}
55
56const noteHtml = computed(() => renderNoteLinks(props.note))
57
58const isOpen = ref(false)
59const buttonRef = ref<HTMLElement>()
60const panelRef = ref<HTMLElement>()
61const panelStyle = ref<Record<string, string>>({})
62
63const mirrorList = computed<string[]>(() => {
64 const raw = props.mirrors
65 const list: string[] = Array.isArray(raw)
66 ? [...raw]
67 : typeof raw === 'string' && raw.trim()
68 ? (() => {
69 try {
70 const parsed: unknown = JSON.parse(raw)
71 return Array.isArray(parsed)
72 ? parsed.filter((u): u is string => typeof u === 'string')
73 : []
74 } catch {
75 return []
76 }
77 })()
78 : []
79 const out: string[] = []
80 const seen = new Set<string>()
81 for (const u of list) {
82 const url = (u ?? '').trim()
83 if (!url || seen.has(url)) continue
84 seen.add(url)
85 out.push(url)
86 }
87 return out
88})
89
90interface UrlParts {
91 key: string
92 pre: string
93 tld: string
94 post: string
95 domain: string
96 isOnion: boolean
97}
98
99/** Split `name.tld/path` (scheme hidden) so the last domain label (`.app`, `.com`) can be bolded. */
100const MAX_URL_CHARS = 32
101const MAX_POST_CHARS = 14
102
103function splitUrl(url: string): UrlParts {
104 let pre: string
105 let tld: string
106 let post: string
107 let domain = ''
108 try {
109 const parsed = new URL(url)
110 const host = parsed.host
111 domain = host.toLowerCase()
112 const displayHost = host.replace(/^www\./i, '')
113 const dot = displayHost.lastIndexOf('.')
114 if (dot > 0) {
115 pre = displayHost.slice(0, dot)
116 tld = displayHost.slice(dot)
117 } else {
118 pre = displayHost
119 tld = ''
120 }
121 post = `${parsed.pathname === '/' ? '/' : parsed.pathname}${parsed.search}${parsed.hash}`
122 } catch {
123 pre = url.replace(/^https?:\/\//i, '')
124 tld = ''
125 post = ''
126 }
127 const isOnion = domain
128 ? domain.endsWith('.onion')
129 : /\.onion(\/|$)/i.test(url)
130
131 // Middle-truncate long URLs: the TLD/end stays visible, the middle shrinks.
132 if (pre.length + tld.length + post.length > MAX_URL_CHARS) {
133 const shownPost = post.length > MAX_POST_CHARS
134 ? post.slice(0, MAX_POST_CHARS - 1) + '…'
135 : post
136 const preBudget = Math.max(10, MAX_URL_CHARS - tld.length - shownPost.length)
137 const shownPre = pre.length > preBudget
138 ? pre.slice(0, preBudget - 1) + '…'
139 : pre
140 return { key: url, pre: shownPre, tld, post: shownPost, domain, isOnion }
141 }
142 return { key: url, pre, tld, post, domain, isOnion }
143}
144
145const rows = computed<UrlParts[]>(() => mirrorList.value.map(splitUrl))
146
147const { faviconsEnabled } = useFavicons()
148const faviconMap = ref<Record<string, string | null>>({})
149
150async function loadFavicons() {
151 if (!faviconsEnabled.value) return
152 for (const row of rows.value) {
153 if (row.isOnion || !row.domain || faviconMap.value[row.key] !== undefined) {
154 continue
155 }
156 faviconMap.value[row.key] = await resolveFaviconUrl(row.domain)
157 }
158}
159
160// Fixed-position panel teleported to <body> so table overflow clipping
161// (and tab containers) can't cut it off — same approach as icon-tip-popup.
162function positionPanel() {
163 const btn = buttonRef.value
164 const panel = panelRef.value
165 if (!btn || !panel) return
166 const rect = btn.getBoundingClientRect()
167 const pw = panel.offsetWidth
168 const ph = panel.offsetHeight
169 const margin = 8
170 let left = rect.left + rect.width / 2 - pw / 2
171 left = Math.max(margin, Math.min(left, window.innerWidth - pw - margin))
172 let top = rect.top - ph - 8
173 if (top < margin) top = rect.bottom + 8
174 if (top + ph > window.innerHeight - margin) {
175 top = Math.max(margin, window.innerHeight - ph - margin)
176 }
177 panelStyle.value = { left: `${left}px`, top: `${top}px` }
178}
179
180function onDocumentClick(e: MouseEvent) {
181 const t = e.target as Node | null
182 if (!t) return
183 if (buttonRef.value?.contains(t)) return
184 if (panelRef.value?.contains(t)) return
185 isOpen.value = false
186}
187
188function onScroll(e: Event) {
189 const t = e.target as Node | null
190 if (t && panelRef.value?.contains(t)) return
191 isOpen.value = false
192}
193
194function onKey(e: KeyboardEvent) {
195 if (e.key === 'Escape') isOpen.value = false
196}
197
198function onResize() {
199 if (isOpen.value) positionPanel()
200}
201
202watch(isOpen, (open) => {
203 if (!open) {
204 document.removeEventListener('click', onDocumentClick, true)
205 document.removeEventListener('scroll', onScroll, true)
206 window.removeEventListener('keydown', onKey)
207 window.removeEventListener('resize', onResize)
208 return
209 }
210 void nextTick(() => {
211 positionPanel()
212 void loadFavicons()
213 })
214 document.addEventListener('click', onDocumentClick, true)
215 document.addEventListener('scroll', onScroll, true)
216 window.addEventListener('keydown', onKey)
217 window.addEventListener('resize', onResize)
218})
219
220watch(faviconsEnabled, (enabled) => {
221 if (enabled && isOpen.value) void loadFavicons()
222})
223</script>
224
225<template>
226 <span ref="buttonRef" class="mirror-wrapper">
227 <button
228 type="button"
229 aria-label="Mirrors"
230 class="mirror-btn size-3 p-0 select-none font-bold cursor-pointer"
231 :aria-expanded="isOpen"
232 @click="isOpen = !isOpen"
233 >
234 <div class="i-material-symbols-directions-alt" />
235 </button>
236 </span>
237
238 <Teleport to="body">
239 <Transition name="mirror-panel">
240 <div
241 v-if="isOpen"
242 ref="panelRef"
243 class="mirror-panel"
244 :style="panelStyle"
245 role="dialog"
246 :aria-label="`Mirrors for ${title}`"
247 >
248 <div class="mirror-head">
249 <span class="mirror-head-title">{{ title }}</span>
250 <span class="mirror-head-count">{{ rows.length }}</span>
251 </div>
252 <p v-if="note" class="mirror-note" :class="noteClass" v-html="noteHtml" />
253 <div class="mirror-scroll">
254 <ul v-if="rows.length" class="mirror-list">
255 <li v-for="row in rows" :key="row.key" class="mirror-item">
256 <a
257 :href="row.key"
258 target="_blank"
259 rel="noopener noreferrer"
260 class="mirror-link"
261 :title="row.key"
262 >
263 <img
264 v-if="faviconsEnabled && !row.isOnion && faviconMap[row.key]"
265 :src="faviconMap[row.key] ?? undefined"
266 class="mirror-favicon"
267 alt=""
268 width="14"
269 height="14"
270 loading="lazy"
271 decoding="async"
272 @error="faviconMap[row.key] = null"
273 />
274 <span
275 v-else-if="row.isOnion"
276 class="i-simple-icons-torbrowser mirror-link-icon"
277 aria-hidden="true"
278 />
279 <span
280 v-else
281 class="i-lucide-globe mirror-link-icon"
282 aria-hidden="true"
283 />
284 <span class="mirror-link-text">{{ row.pre }}<strong class="mirror-tld">{{ row.tld }}</strong>{{ row.post }}</span>
285 </a>
286 </li>
287 </ul>
288 <p v-else class="mirror-empty">No mirrors listed yet.</p>
289 </div>
290 </div>
291 </Transition>
292 </Teleport>
293</template>
294
295<style scoped>
296.mirror-wrapper {
297 display: inline-flex !important;
298 vertical-align: -0.125em;
299}
300
301.mirror-btn {
302 color: var(--vp-c-brand-1);
303}
304
305.mirror-panel {
306 position: fixed;
307 z-index: 9999;
308 width: 282px;
309 max-width: calc(100vw - 24px);
310 background-color: var(--vp-c-bg-elv);
311 border: 2px solid #3d3d3d;
312 border-radius: 12px;
313 box-shadow: var(--vp-shadow-3);
314 transform-origin: top center;
315 overflow: hidden;
316}
317
318.mirror-head {
319 display: flex;
320 align-items: center;
321 gap: 8px;
322 padding: 10px 12px 6px;
323 user-select: none;
324}
325
326.mirror-head-title {
327 flex: 1;
328 min-width: 0;
329 overflow: hidden;
330 white-space: nowrap;
331 text-overflow: ellipsis;
332 font-size: 14px;
333 font-weight: 600;
334 color: var(--vp-c-text-1);
335}
336
337.mirror-head-count {
338 flex: none;
339 font-size: 11px;
340 font-weight: 600;
341 color: var(--vp-c-text-3);
342 border: 1px solid var(--vp-c-divider);
343 border-radius: 999px;
344 padding: 0 7px;
345 line-height: 18px;
346}
347
348.mirror-scroll {
349 max-height: 280px;
350 overflow-y: auto;
351 overflow-x: hidden;
352 overscroll-behavior: contain;
353 padding: 4px 8px 10px;
354}
355
356.mirror-list {
357 list-style: none;
358 padding: 0;
359 margin: 0;
360 display: flex;
361 flex-direction: column;
362 gap: 2px;
363}
364
365.mirror-item {
366 display: flex;
367 align-items: center;
368 gap: 6px;
369 border-radius: 8px;
370 padding: 2px 4px;
371 transition: background-color 0.15s;
372}
373
374.mirror-item:hover {
375 background: var(--vp-c-default-soft);
376}
377
378.mirror-link {
379 display: flex;
380 align-items: center;
381 gap: 6px;
382 flex: 1;
383 min-width: 0;
384 padding: 4px 6px;
385 font-size: 13px;
386 color: var(--vp-c-text-2);
387 text-decoration: none;
388 transition: color 0.15s;
389}
390
391.mirror-link:hover {
392 color: var(--vp-c-brand-1);
393}
394
395.mirror-link-icon {
396 flex: none;
397 font-size: 12px;
398 color: var(--vp-c-text-3);
399}
400
401.mirror-favicon {
402 flex: none;
403 width: 14px;
404 height: 14px;
405 border-radius: 3px;
406}
407
408.mirror-link-text {
409 flex: 1;
410 min-width: 0;
411 overflow: hidden;
412 white-space: nowrap;
413 text-overflow: ellipsis;
414}
415
416.mirror-tld {
417 font-weight: 700;
418 color: var(--vp-c-text-1);
419}
420
421.mirror-empty {
422 margin: 0;
423 padding: 8px 6px;
424 font-size: 13px;
425 color: var(--vp-c-text-3);
426}
427
428.mirror-note {
429 margin: 2px 8px 6px;
430 padding: 6px 8px;
431 font-size: 12px;
432 line-height: 1.5;
433 border: 1px solid;
434 border-radius: 8px;
435}
436
437.mirror-note--info {
438 color: var(--vp-custom-block-info-text);
439 background-color: var(--vp-custom-block-info-bg);
440 border-color: var(--vp-custom-block-info-border);
441}
442
443.mirror-note--tip {
444 color: var(--vp-custom-block-tip-text);
445 background-color: var(--vp-custom-block-tip-bg);
446 border-color: var(--vp-custom-block-tip-border);
447}
448
449.mirror-note--warning {
450 color: var(--vp-custom-block-warning-text);
451 background-color: var(--vp-custom-block-warning-bg);
452 border-color: var(--vp-custom-block-warning-border);
453}
454
455.mirror-note--danger {
456 color: var(--vp-custom-block-danger-text);
457 background-color: var(--vp-custom-block-danger-bg);
458 border-color: var(--vp-custom-block-danger-border);
459}
460
461.mirror-note :deep(a) {
462 color: inherit;
463 font-weight: 600;
464 text-decoration: underline dashed;
465 text-underline-offset: 3px;
466 text-decoration-thickness: 1px;
467}
468
469.mirror-panel-enter-active,
470.mirror-panel-leave-active {
471 transition: opacity 0.15s, transform 0.15s cubic-bezier(0.16, 1, 0.3, 1);
472}
473
474.mirror-panel-enter-from,
475.mirror-panel-leave-to {
476 opacity: 0;
477 transform: scale(0.95) translateY(4px);
478}
479
480</style>
docs/.vitepress/theme/composables/useFavicons.ts +6
@@ -24,6 +24,12 @@ function getFaviconManifest() {
24 return faviconManifestPromise 24 return faviconManifestPromise
25} 25}
26 26
27export async function resolveFaviconUrl(domain: string): Promise<string | null> {
28 const icons = await getFaviconManifest()
29 const path = icons[domain.toLowerCase()]
30 return path ? `${FAVICON_BASE_URL}${path}` : null
31}
32
27function showGlobeFallback(el: HTMLElement) { 33function showGlobeFallback(el: HTMLElement) {
28 const span = document.createElement('span') 34 const span = document.createElement('span')
29 span.className = 'wk-favicon wk-favicon-fallback i-lucide:globe' 35 span.className = 'wk-favicon wk-favicon-fallback i-lucide:globe'
docs/.vitepress/theme/globalComponents.ts +2
@@ -7,6 +7,7 @@ import Fb from './components/Fb.vue'
7import Feedback from './components/Feedback.vue' 7import Feedback from './components/Feedback.vue'
8import Highlight from './components/Highlight.vue' 8import Highlight from './components/Highlight.vue'
9import LinkInline from './components/LinkInline.vue' 9import LinkInline from './components/LinkInline.vue'
10import MirrorTooltip from './components/MirrorTooltip.vue'
10import ScrapeTable from './components/ScrapeTable.vue' 11import ScrapeTable from './components/ScrapeTable.vue'
11import Tooltip from './components/Tooltip.vue' 12import Tooltip from './components/Tooltip.vue'
12 13
@@ -16,6 +17,7 @@ export function registerGlobalComponents(app: App) {
16 app.component('Block', Block) 17 app.component('Block', Block)
17 app.component('Authors', Authors) 18 app.component('Authors', Authors)
18 app.component('Tooltip', Tooltip) 19 app.component('Tooltip', Tooltip)
20 app.component('MirrorTooltip', MirrorTooltip)
19 app.component('Feedback', Feedback) 21 app.component('Feedback', Feedback)
20 app.component('fb', Fb) 22 app.component('fb', Fb)
21 app.component('Collapsible', Collapsible) 23 app.component('Collapsible', Collapsible)
docs/.vitepress/utils/mirrors.ts added +94
@@ -0,0 +1,94 @@
1/**
2 * All Rights Reserved
3 *
4 * Copyright (c) 2025 taskylizard
5 *
6 * All rights reserved. This code and its associated files may not be copied, modified, distributed, sublicensed, or used in any form, in whole or in part, without prior written permission from the copyright holder.
7 */
8import matter from 'gray-matter'
9import { readdirSync, readFileSync } from 'node:fs'
10import { basename, join, resolve } from 'pathe'
11
12export interface MirrorData {
13 id: string
14 title: string
15 src: string
16 mirrors: string[]
17 note: string
18 noteType: string
19 frontmatter: Record<string, string>
20 content: string
21}
22
23const NOTE_TYPE_KEYS = ['danger', 'warning', 'tip', 'info'] as const
24
25const URL_RE = /https?:\/\/[^\s<>"')\]]+/g
26
27export function extractUrls(text: string): string[] {
28 const out: string[] = []
29 const seen = new Set<string>()
30 for (const m of text.matchAll(URL_RE)) {
31 const url = m[0].replace(/[.,;:!?]+$/, '')
32 if (!seen.has(url)) {
33 seen.add(url)
34 out.push(url)
35 }
36 }
37 return out
38}
39
40let mirrorsCache: MirrorData[] | null = null
41
42export function loadMirrors(): MirrorData[] {
43 if (mirrorsCache) return mirrorsCache
44
45 const mirrorsDir = resolve(process.cwd(), 'docs/.vitepress/mirrors')
46 const mirrors: MirrorData[] = []
47
48 try {
49 const files = readdirSync(mirrorsDir).filter((file) => file.endsWith('.md'))
50
51 for (const file of files) {
52 const filePath = join(mirrorsDir, file)
53 const fileContent = readFileSync(filePath, 'utf-8')
54 const { data, content } = matter(fileContent)
55
56 const id = basename(file, '.md')
57 const src = typeof data.src === 'string' ? data.src.trim() : ''
58 const title = typeof data.title === 'string' && data.title.trim()
59 ? data.title.trim()
60 : id
61 const noteEntry = NOTE_TYPE_KEYS.map((t) => ({
62 type: t,
63 value: (data as Record<string, unknown>)[t]
64 })).find((e) => typeof e.value === 'string' && e.value.trim())
65 const note = noteEntry ? (noteEntry.value as string).trim() : ''
66 const noteType = noteEntry ? noteEntry.type : 'warning'
67 const cleanContent = content.trim()
68 const mirrorsList = extractUrls(cleanContent).filter((u) => u !== src)
69
70 mirrors.push({
71 id,
72 title,
73 src,
74 mirrors: mirrorsList,
75 note,
76 noteType,
77 frontmatter: data as Record<string, string>,
78 content: cleanContent
79 })
80 }
81 } catch (error) {
82 console.warn('Failed to load mirrors:', error)
83 }
84
85 mirrorsCache = mirrors
86 return mirrors
87}
88
89export function getMirror(id: string): MirrorData | undefined {
90 const mirrors = loadMirrors()
91 return mirrors.find((mirror) => mirror.id === id)
92}
93
94export const mirrors = loadMirrors()