@windcoder/astro-theme-orchid 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +5 -3
  2. package/package.json +4 -2
  3. package/scripts/check-friends.mjs +227 -0
  4. package/scripts/generate-lqips.mjs +234 -20
  5. package/scripts/migrate-posts.mjs +375 -0
  6. package/src/components/AlbumCard.astro +4 -1
  7. package/src/components/Analytics.astro +3 -0
  8. package/src/components/BaseLayout.astro +222 -39
  9. package/src/components/DisplaySettings.astro +383 -0
  10. package/src/components/Header.astro +56 -2
  11. package/src/components/MusicPlayer.astro +45 -5
  12. package/src/components/MusicWidget.astro +265 -0
  13. package/src/components/PhotoCard.astro +13 -1
  14. package/src/components/PostCard.astro +4 -1
  15. package/src/components/SakuraEffect.astro +126 -28
  16. package/src/components/Sidebar.astro +28 -7
  17. package/src/components/analytics/WebVitals.astro +72 -0
  18. package/src/i18n/en.ts +42 -0
  19. package/src/i18n/ja.ts +213 -0
  20. package/src/i18n/ko.ts +212 -0
  21. package/src/i18n/resolve.ts +10 -1
  22. package/src/i18n/ru.ts +213 -0
  23. package/src/i18n/zh-CN.ts +43 -0
  24. package/src/i18n/zh-TW.ts +208 -0
  25. package/src/index.ts +23 -0
  26. package/src/plugins/rehype.ts +76 -4
  27. package/src/routes/bangumi.astro +110 -0
  28. package/src/routes/friends.astro +10 -2
  29. package/src/routes/manifest.webmanifest.ts +33 -0
  30. package/src/routes/page/[page].astro +3 -0
  31. package/src/routes/search.astro +24 -0
  32. package/src/routes/sponsor.astro +17 -4
  33. package/src/routes/sw.js.ts +127 -0
  34. package/src/schema.ts +446 -45
  35. package/src/scripts/app.ts +805 -37
  36. package/src/styles/global.css +939 -18
  37. package/src/utils/gallery.ts +3 -1
  38. package/src/utils/image.ts +79 -0
  39. package/src/utils/lqip.ts +21 -12
  40. package/src/utils/thumb.ts +26 -0
  41. package/src/vite.ts +95 -8
package/README.md CHANGED
@@ -2,13 +2,15 @@
2
2
 
3
3
  清新简约的 Astro 博客主题,以 **Astro Integration** 形式提供:站点只做三件事——声明域名、接入主题、传入配置;页面、样式引擎、路由全部由主题注入。支持版本化升级与组件覆盖(`src/overrides/` 同名替换,升级永不覆盖站点定制)。
4
4
 
5
+ > 部分功能设计参考了 [Firefly](https://github.com/CuteLeaf/Firefly) 主题,在此致谢。
6
+
5
7
  ## 特性一览
6
8
 
7
- - **页面**:首页(featured/cover/compact/text 四种卡片混排)、文章页(TOC/相关推荐/分享海报/打赏入口)、归档(按年折叠)、分类、标签、专题、画廊(含加密相册)、友链、留言板、打赏、关于
9
+ - **页面**:首页(featured/cover/compact/text 四种卡片混排)、文章页(TOC/相关推荐/分享海报/打赏入口)、归档(按年折叠)、分类、标签、专题、画廊(含加密相册)、友链、追番、留言板、打赏、关于
8
10
  - **写作增强**:LaTeX(KaTeX + mhchem)、Mermaid 双主题、PlantUML、Callouts、GitHub 卡片、图语法(figure/九宫格)、Expressive Code 代码块(双主题/行号/折叠/复制/语言徽标)、邮箱防爬
9
11
  - **互动系统**:评论五套(Artalk / Twikoo / Waline / Giscus / Disqus)、文章加密、过时提醒、公告、广告位
10
12
  - **个性化**:深浅模式、hue 动态调色、樱花飘落、背景壁纸、音乐播放器(跨页不断播)、Live2D 看板娘、i18n(zh-CN / en)
11
- - **工程化**:配置启动即校验(Zod)、OG 分享图、LQIP 占位、字体子集化、站点统计四件套(GA / Clarity / Umami / 51.la)、RSS / sitemap
13
+ - **工程化**:配置启动即校验(Zod)、OG 分享图、LQIP 占位、字体子集化、站点统计四件套(GA / Clarity / Umami / 51.la)、RSS / sitemap、PWA 可安装(manifest + 离线兜底 Service Worker)
12
14
 
13
15
  ## 快速上手
14
16
 
@@ -81,7 +83,7 @@ site/
81
83
  完整配置说明与文章 frontmatter 全字段表统一放在 demo 站「主题使用指南」系列文章(源文件在本仓库 `site/src/content/posts/`),按主题分组:
82
84
 
83
85
  - 基础:《站点基础配置》|《导航栏》|《首页横幅》|《侧边栏与小组件》|《个人资料卡》|《版权声明》|《文章列表与归档》
84
- - 功能:《文章页功能》|《内容渲染》|《樱花特效》|《音乐播放器》|《Live2D 看板娘》|《字体》|《评论系统》|《公告》|《站点统计》|《广告位》|《友链》|《赞助》|《画廊》|《独立页面》
86
+ - 功能:《文章页功能》|《内容渲染》|《樱花特效》|《音乐播放器》|《Live2D 看板娘》|《字体》|《评论系统》|《公告》|《站点统计》|《广告位》|《友链》|《追番》|《PWA》|《赞助》|《画廊》|《独立页面》
85
87
  - 写作:《写作指南》(frontmatter 全字段与增强语法)|《MDX 指南》(MDX 启用与踩坑修复)
86
88
 
87
89
  ## 定制与覆盖
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windcoder/astro-theme-orchid",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "清新简约的 Astro 博客主题,以 Integration 形式提供,支持版本化升级与组件覆盖",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -64,7 +64,9 @@
64
64
  "satori": "^0.47.1",
65
65
  "sharp": "^0.35.5",
66
66
  "subset-font": "^2.5.0",
67
- "tailwindcss": "^4.3.2"
67
+ "tailwindcss": "^4.3.2",
68
+ "web-vitals": "^6.2.3",
69
+ "yaml": "^2.9.1"
68
70
  },
69
71
  "devDependencies": {
70
72
  "@types/pako": "^2.0.3",
@@ -0,0 +1,227 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 友链存活检测(§4.90):读取构建产物 dist/friends/index.html,抽取友链卡片
4
+ * (a.friend-card + .friend-name),并发探测各站点可达性,输出检测报告。
5
+ *
6
+ * 设计为发布后/定时(CI cron)手动运行,不挂进 build——构建保持离线可复现。
7
+ *
8
+ * 用法(站点根目录):
9
+ * node node_modules/@windcoder/astro-theme-orchid/scripts/check-friends.mjs \
10
+ * [--dist dist] [--timeout 8000] [--retries 1] [--concurrency 6] \
11
+ * [--json report.json] [--fail-on-dead]
12
+ *
13
+ * 判级:ok = 2xx/3xx;warn = 403/405/406/429/999(常见反爬拦截,未必失联);
14
+ * dead = 网络层失败(解析/超时/拒绝)与其余 4xx/5xx。网络层失败与 5xx 重试。
15
+ */
16
+ import { readFileSync, writeFileSync } from "node:fs";
17
+ import { resolve } from "node:path";
18
+ import { pathToFileURL } from "node:url";
19
+
20
+ const UA =
21
+ "Mozilla/5.0 (compatible; OrchidFriendChecker/+https://github.com/iwinder/qy-astro-theme-orchid)";
22
+ /** 这些状态码通常是 WAF/反爬拦截而非失联,只警告不定罪 */
23
+ const WARN_CODES = new Set([403, 405, 406, 429, 999]);
24
+
25
+ function parseArgs(argv) {
26
+ const args = {
27
+ dist: "dist",
28
+ timeout: 8000,
29
+ retries: 1,
30
+ concurrency: 6,
31
+ json: "",
32
+ failOnDead: false,
33
+ };
34
+ for (let i = 0; i < argv.length; i++) {
35
+ const a = argv[i];
36
+ if (a === "--dist") args.dist = argv[++i];
37
+ else if (a === "--timeout") args.timeout = Number(argv[++i]);
38
+ else if (a === "--retries") args.retries = Number(argv[++i]);
39
+ else if (a === "--concurrency") args.concurrency = Number(argv[++i]);
40
+ else if (a === "--json") args.json = argv[++i];
41
+ else if (a === "--fail-on-dead") args.failOnDead = true;
42
+ else if (a === "--help" || a === "-h") {
43
+ console.log(
44
+ "用法:node check-friends.mjs [--dist dist] [--timeout 8000] [--retries 1] [--concurrency 6] [--json report.json] [--fail-on-dead]",
45
+ );
46
+ process.exit(0);
47
+ }
48
+ }
49
+ return args;
50
+ }
51
+
52
+ function decodeEntities(s) {
53
+ return s
54
+ .replace(/&amp;/g, "&")
55
+ .replace(/&lt;/g, "<")
56
+ .replace(/&gt;/g, ">")
57
+ .replace(/&quot;/g, '"')
58
+ .replace(/&#39;/g, "'");
59
+ }
60
+
61
+ /** 从友链页 HTML 抽取 [{ title, url }](主题自有标记,结构稳定) */
62
+ export function extractFriends(html) {
63
+ const out = [];
64
+ const re =
65
+ /<a class="friend-card card" href="([^"]+)"[\s\S]*?<div class="friend-name">([\s\S]*?)<\/div>/g;
66
+ let m;
67
+ while (true) {
68
+ m = re.exec(html);
69
+ if (!m) break;
70
+ out.push({
71
+ url: decodeEntities(m[1]),
72
+ title: decodeEntities(m[2].replace(/<[^>]+>/g, "")).trim(),
73
+ });
74
+ }
75
+ return out;
76
+ }
77
+
78
+ /** HTTP 状态码 → ok/warn/dead 判级(0 = 网络层失败) */
79
+ export function classify(code) {
80
+ if (code === 0) return "dead";
81
+ if (code >= 200 && code < 400) return "ok";
82
+ if (WARN_CODES.has(code)) return "warn";
83
+ return "dead";
84
+ }
85
+
86
+ /** 单次探测:GET + 超时 + 立即丢弃响应体(只看状态码) */
87
+ async function probeOnce(url, timeout) {
88
+ const started = Date.now();
89
+ try {
90
+ const res = await fetch(url, {
91
+ redirect: "follow",
92
+ signal: AbortSignal.timeout(timeout),
93
+ headers: { "user-agent": UA, accept: "text/html,*/*;q=0.8" },
94
+ });
95
+ res.body?.cancel().catch(() => {});
96
+ return { code: res.status, ms: Date.now() - started, msg: "" };
97
+ } catch (err) {
98
+ const cause = err?.cause?.code ?? err?.code ?? "";
99
+ const msg =
100
+ err?.name === "TimeoutError" || err?.name === "AbortError"
101
+ ? "超时"
102
+ : cause === "ENOTFOUND" || cause === "EAI_AGAIN"
103
+ ? "域名无法解析"
104
+ : cause === "ECONNREFUSED"
105
+ ? "连接被拒绝"
106
+ : cause === "ECONNRESET"
107
+ ? "连接被重置"
108
+ : cause === "CERT_HAS_EXPIRED" ||
109
+ cause === "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
110
+ ? "证书异常"
111
+ : String(cause || err?.message || err);
112
+ return { code: 0, ms: Date.now() - started, msg };
113
+ }
114
+ }
115
+
116
+ /** 带重试探测:网络层失败与 5xx 重试(4xx 定局重试无意义) */
117
+ export async function probe(url, { timeout, retries }) {
118
+ let last = await probeOnce(url, timeout);
119
+ for (let i = 0; i < retries && (last.code === 0 || last.code >= 500); i++) {
120
+ last = await probeOnce(url, timeout);
121
+ }
122
+ return { ...last, state: classify(last.code) };
123
+ }
124
+
125
+ /** CJK 感知的终端定宽 */
126
+ function pad(s, width) {
127
+ let visual = 0;
128
+ for (const ch of s) visual += ch.codePointAt(0) > 0xff ? 2 : 1;
129
+ return visual >= width ? s : s + " ".repeat(width - visual);
130
+ }
131
+
132
+ async function main() {
133
+ const args = parseArgs(process.argv.slice(2));
134
+ const pagePath = resolve(args.dist, "friends", "index.html");
135
+ let html;
136
+ try {
137
+ html = readFileSync(pagePath, "utf8");
138
+ } catch {
139
+ console.error(
140
+ `[check-friends] 找不到 ${pagePath}\n 友链页未开启(pages.friends: false)或尚未构建;先 pnpm build 再检测。`,
141
+ );
142
+ process.exit(0);
143
+ }
144
+
145
+ const friends = extractFriends(html);
146
+ if (!friends.length) {
147
+ console.log("[check-friends] 友链页无友链卡片,无事可做。");
148
+ process.exit(0);
149
+ }
150
+ console.log(
151
+ `[check-friends] 共 ${friends.length} 条友链,并发 ${args.concurrency},超时 ${args.timeout}ms,重试 ${args.retries} 次\n`,
152
+ );
153
+
154
+ const results = new Array(friends.length);
155
+ let cursor = 0;
156
+ async function worker() {
157
+ while (cursor < friends.length) {
158
+ const idx = cursor++;
159
+ const { url, title } = friends[idx];
160
+ process.stdout.write(` 探测 ${title} …\r`);
161
+ const r = await probe(url, args);
162
+ results[idx] = { ...r, title, url };
163
+ }
164
+ }
165
+ await Promise.all(
166
+ Array.from({ length: Math.min(args.concurrency, friends.length) }, worker),
167
+ );
168
+
169
+ const ICON = { ok: "✓", warn: "⚠", dead: "✗" };
170
+ console.log(
171
+ "\n┌────┬──────┬────────┬────────┬──────────────────────┬──────────────────────────────────────┐",
172
+ );
173
+ console.log(
174
+ `│ ${pad("状态", 2)} │ ${pad("站点", 18)} │ ${pad("HTTP", 6)} │ ${pad("耗时", 6)} │ ${pad("说明", 20)} │ 链接`,
175
+ );
176
+ console.log(
177
+ "├────┼──────┼────────┼────────┼──────────────────────┼──────────────────────────────────────┤",
178
+ );
179
+ for (const r of results) {
180
+ const note = r.state === "warn" ? "疑似反爬拦截,请人工复核" : r.msg;
181
+ console.log(
182
+ `│ ${ICON[r.state]} │ ${pad(r.title, 18)} │ ${pad(String(r.code || "-"), 6)} │ ${pad(`${r.ms}ms`, 6)} │ ${pad(note, 20)} │ ${r.url}`,
183
+ );
184
+ }
185
+ console.log(
186
+ "└────┴──────┴────────┴────────┴──────────────────────┴──────────────────────────────────────┘",
187
+ );
188
+
189
+ const ok = results.filter((r) => r.state === "ok").length;
190
+ const warn = results.filter((r) => r.state === "warn").length;
191
+ const dead = results.filter((r) => r.state === "dead").length;
192
+ console.log(`\n[check-friends] 完成:ok ${ok} / warn ${warn} / dead ${dead}`);
193
+ if (warn)
194
+ console.log(
195
+ " ⚠ warn 为常见反爬状态码(403/405/406/429/999),浏览器开一下再决定是否下架",
196
+ );
197
+ if (dead) {
198
+ for (const r of results.filter((x) => x.state === "dead"))
199
+ console.log(` ✗ ${r.title} <${r.url}> ${r.msg || `HTTP ${r.code}`}`);
200
+ }
201
+
202
+ if (args.json) {
203
+ const report = {
204
+ checkedAt: new Date().toISOString(),
205
+ total: friends.length,
206
+ ok,
207
+ warn,
208
+ dead,
209
+ results: results.map(({ title, url, state, code, ms, msg }) => ({
210
+ title,
211
+ url,
212
+ state,
213
+ code,
214
+ ms,
215
+ msg,
216
+ })),
217
+ };
218
+ writeFileSync(resolve(args.json), `${JSON.stringify(report, null, 2)}\n`);
219
+ console.log(` 报告已写入 ${resolve(args.json)}`);
220
+ }
221
+
222
+ if (args.failOnDead && dead > 0) process.exit(1);
223
+ }
224
+
225
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
226
+ main();
227
+ }
@@ -1,25 +1,46 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * LQIP 生成脚本(M3b-b9,P1-14):扫描站点 public 下的图片,每张采样
4
- * 2×2 像素取三色,产出 18 字符 compact hex(三段 rgb hex 拼接),
5
- * 整体写入站点根 lqips.json(键 → 色,全量重建,增量收益有限故不做)。
3
+ * LQIP + 缩略图生成脚本(M3b-b9,P1-14;§4.106 扩展双产物;§4.107 外链 LQIP):
4
+ * 产出两份构建期元数据:
5
+ * 1. lqips.json:每张采样 2×2 像素取三色 → 18 字符 compact hex(三段 rgb hex 拼接)。
6
+ * 两类键:`public:<posix 相对路径>`(站点 public 图片)+ `url:<完整外链 URL>`
7
+ * (文章封面/正文首图/相册 urls.txt 等外链图,fetch 下载后同样采样——
8
+ * 缓存即产物自身:已有 url: 键不重复抓取,`--refresh` 强制重抓)。
9
+ * 2. thumbs.json:每张 public 图同步生成同目录 `<名>.thumb.webp`(480 宽 q75,
10
+ * 不放大小图),并记录原图宽高(灯箱打开原图时需正确原始尺寸)。
11
+ * 外链图不做缩略图(版权/CORS/构建网络依赖,消费端回退原图)。
6
12
  *
7
13
  * 运行:pnpm --filter site lqip(cwd 必须是 site 根)
8
- * 消费链路:lqips.json → themeLqipsPlugin(vite.ts)→ virtual:theme/lqips
9
- * → utils/lqip.ts getLqipStyle() → 构建期内联渐变(零客户端请求)。
14
+ * 消费链路:
15
+ * lqips.json → themeLqipsPlugin(vite.ts)→ virtual:theme/lqips
16
+ * → utils/lqip.ts getLqipStyle() / rehypeImageEnhance() → 构建期内联渐变;
17
+ * thumbs.json → themeLqipsPlugin(vite.ts)→ virtual:theme/thumbs
18
+ * → utils/thumb.ts getThumbInfo() → 列表封面构建期换缩略图 URL。
10
19
  *
11
- * 键约定:`public:<posix 相对路径>`。主题图片一律 public 路径或外链
12
- * (不用 astro:assets),故无需 src: 键;外链/无数据在消费端自然降级纯色。
13
- * sharp 经本脚本文件位置解析到 theme 包依赖,与 cwd 无关。
20
+ * 外键一致性约定:url: 键的 URL 必须与渲染期逐字符一致——
21
+ * - frontmatter image / 正文首图 / urls.txt 行:原样提取(与 gallery.ts 的
22
+ * trim + `#` 注释过滤规则相同);
23
+ * - image:"api":复刻 utils.ts 的 randomCoverUrl(seedHash + ?v= 追加),
24
+ * apis 模板从 site/src/config/*.ts 正则提取首个 apis 数组。
25
+ * 相册「显式外链 cover」(相册元数据字段)暂不收集:demo 站无此用法,
26
+ * 且元数据格式多样,出现需求时再扩展。sharp 经本脚本位置解析 theme 依赖。
14
27
  */
15
28
  import fs from "node:fs";
16
29
  import path from "node:path";
17
- import { fileURLToPath } from "node:url";
18
30
  import sharp from "sharp";
19
31
 
20
32
  const cwd = process.cwd();
21
33
  const publicDir = path.join(cwd, "public");
22
- const outFile = path.join(cwd, "lqips.json");
34
+ const srcDir = path.join(cwd, "src");
35
+ const lqipFile = path.join(cwd, "lqips.json");
36
+ const thumbsFile = path.join(cwd, "thumbs.json");
37
+
38
+ const THUMB_WIDTH = 480;
39
+ const THUMB_QUALITY = 75;
40
+ const THUMB_SUFFIX = ".thumb.webp";
41
+ const FETCH_CONCURRENCY = 5;
42
+ const FETCH_TIMEOUT_MS = 15_000;
43
+ const REFRESH = process.argv.includes("--refresh");
23
44
 
24
45
  const EXTS = new Set([".png", ".jpg", ".jpeg", ".webp", ".avif"]);
25
46
  const EXCLUDED_DIRS = new Set(["node_modules", ".astro", "dist", ".git"]);
@@ -29,7 +50,7 @@ if (!fs.existsSync(publicDir)) {
29
50
  process.exit(1);
30
51
  }
31
52
 
32
- /** 递归收集图片相对路径(posix 风格,排除构建/依赖目录) */
53
+ /** 递归收集图片相对路径(posix 风格,排除构建/依赖目录与缩略图产物) */
33
54
  function collectImages(dir, base = "") {
34
55
  const out = [];
35
56
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
@@ -41,7 +62,10 @@ function collectImages(dir, base = "") {
41
62
  base ? `${base}/${entry.name}` : entry.name,
42
63
  ),
43
64
  );
44
- } else if (EXTS.has(path.extname(entry.name).toLowerCase())) {
65
+ } else if (
66
+ EXTS.has(path.extname(entry.name).toLowerCase()) &&
67
+ !entry.name.endsWith(THUMB_SUFFIX)
68
+ ) {
45
69
  out.push(base ? `${base}/${entry.name}` : entry.name);
46
70
  }
47
71
  }
@@ -49,8 +73,8 @@ function collectImages(dir, base = "") {
49
73
  }
50
74
 
51
75
  /** sharp 2×2 fill 采样 → 取 [0][1][3] 三像素(左上/右上/右下)rgb hex 拼接 */
52
- async function sampleColors(file) {
53
- const { data, info } = await sharp(file)
76
+ async function sampleColors(input) {
77
+ const { data, info } = await sharp(input)
54
78
  .resize(2, 2, { fit: "fill" })
55
79
  .removeAlpha()
56
80
  .raw()
@@ -64,19 +88,209 @@ async function sampleColors(file) {
64
88
  return hex(0) + hex(1) + hex(3);
65
89
  }
66
90
 
91
+ /** 生成 480 宽 webp 缩略图(不放大小图),返回 { thumb 相对路径, 原图宽高 } */
92
+ async function makeThumb(rel) {
93
+ const file = path.join(publicDir, rel);
94
+ const parsed = path.parse(rel);
95
+ const thumbRel = path.posix.format({
96
+ dir: parsed.dir,
97
+ name: `${parsed.name}.thumb`,
98
+ ext: ".webp",
99
+ });
100
+ const meta = await sharp(file).metadata();
101
+ await sharp(file)
102
+ .resize({ width: THUMB_WIDTH, withoutEnlargement: true })
103
+ .webp({ quality: THUMB_QUALITY })
104
+ .toFile(path.join(publicDir, thumbRel));
105
+ return {
106
+ thumb: thumbRel,
107
+ width: meta.width ?? 0,
108
+ height: meta.height ?? 0,
109
+ };
110
+ }
111
+
112
+ // ---------- 外链 URL 收集(§4.107) ----------
113
+
114
+ /** 复刻 utils.ts seedHash(Java String.hashCode 同款),保证与渲染期键一致 */
115
+ function seedHash(str) {
116
+ let h = 0;
117
+ for (let i = 0; i < str.length; i++)
118
+ h = ((h << 5) - h + str.charCodeAt(i)) | 0;
119
+ return Math.abs(h);
120
+ }
121
+
122
+ /** 复刻 utils.ts randomCoverUrl:{slug} 替换 + ?v=<hash>(有 query 用 &) */
123
+ function randomCoverUrl(template, slug) {
124
+ const withSlug = template.includes("{slug}")
125
+ ? template.replaceAll("{slug}", slug)
126
+ : template;
127
+ return `${withSlug}${withSlug.includes("?") ? "&" : "?"}v=${seedHash(slug)}`;
128
+ }
129
+
130
+ /** 从 site/src/config/*.ts 正则提取首个 randomCover.apis 模板(提取不到返回 null) */
131
+ function getApiTemplate() {
132
+ const configDir = path.join(srcDir, "config");
133
+ if (!fs.existsSync(configDir)) return null;
134
+ for (const name of fs.readdirSync(configDir).sort()) {
135
+ if (!/\.(m|c)?(ts|js)$/.test(name)) continue;
136
+ const text = fs.readFileSync(path.join(configDir, name), "utf8");
137
+ const apis = text.match(/apis:\s*\[([^\]]*)\]/);
138
+ if (apis) {
139
+ const url = apis[1].match(/["']([^"']+)["']/);
140
+ if (url) return url[1];
141
+ }
142
+ }
143
+ return null;
144
+ }
145
+
146
+ /** 正文首个外链图 URL:跳过 ```/~~~ 围栏代码块,md 图片语法或 <img> 均可 */
147
+ function extractFirstImage(body) {
148
+ let inFence = false;
149
+ for (const line of body.split("\n")) {
150
+ if (/^\s*(```|~~~)/.test(line)) {
151
+ inFence = !inFence;
152
+ continue;
153
+ }
154
+ if (inFence) continue;
155
+ let m = line.match(/!\[[^\]]*\]\(\s*(https?:\/\/[^)\s]+)/);
156
+ if (m) return m[1];
157
+ m = line.match(/<img[^>]*\ssrc=["'](https?:\/\/[^"']+)["']/i);
158
+ if (m) return m[1];
159
+ }
160
+ return null;
161
+ }
162
+
163
+ /** 收集外链图片 URL:文章 frontmatter image(含 api 确定性解析)+ 正文首图 + 相册 urls.txt */
164
+ function collectRemoteUrls() {
165
+ const urls = new Set();
166
+ const apiTemplate = getApiTemplate();
167
+ const postsDir = path.join(srcDir, "content", "posts");
168
+ if (fs.existsSync(postsDir)) {
169
+ const walkMd = (dir) => {
170
+ const out = [];
171
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
172
+ if (entry.isDirectory()) out.push(...walkMd(path.join(dir, entry.name)));
173
+ else if (/\.(md|mdx)$/i.test(entry.name)) out.push(path.join(dir, entry.name));
174
+ }
175
+ return out;
176
+ };
177
+ for (const file of walkMd(postsDir)) {
178
+ const text = fs.readFileSync(file, "utf8");
179
+ const fm = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
180
+ let image;
181
+ if (fm) {
182
+ const im = fm[1].match(/^image:\s*["']?([^"'\n]+?)["']?\s*$/m);
183
+ if (im) image = im[1].trim();
184
+ }
185
+ if (image && image !== "api" && /^https?:\/\//.test(image)) {
186
+ urls.add(image);
187
+ } else if (image === "api" && apiTemplate) {
188
+ const slug = path.basename(file).replace(/\.(md|mdx)$/i, "");
189
+ urls.add(randomCoverUrl(apiTemplate, slug));
190
+ }
191
+ // 正文首图(无封面文章它是列表封面;有封面文章供正文增强查表)
192
+ const body = fm ? text.slice(fm[0].length) : text;
193
+ const first = extractFirstImage(body);
194
+ if (first) urls.add(first);
195
+ }
196
+ }
197
+ const galleryDir = path.join(publicDir, "gallery");
198
+ if (fs.existsSync(galleryDir)) {
199
+ for (const entry of fs.readdirSync(galleryDir, { withFileTypes: true })) {
200
+ if (!entry.isDirectory()) continue;
201
+ const urlsFile = path.join(galleryDir, entry.name, "urls.txt");
202
+ if (!fs.existsSync(urlsFile)) continue;
203
+ for (const line of fs.readFileSync(urlsFile, "utf-8").split("\n")) {
204
+ const u = line.trim();
205
+ if (u && !u.startsWith("#") && /^https?:\/\//.test(u)) urls.add(u);
206
+ }
207
+ }
208
+ }
209
+ return [...urls];
210
+ }
211
+
212
+ /** fetch 外链图 → sharp 采样(超时/非 2xx 抛错由调用方跳过) */
213
+ async function fetchSample(url) {
214
+ const res = await fetch(url, {
215
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
216
+ headers: { "user-agent": "orchid-theme-lqip/1.0" },
217
+ });
218
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
219
+ return sampleColors(Buffer.from(await res.arrayBuffer()));
220
+ }
221
+
222
+ /** 固定并发的小任务池(保持顺序写 out) */
223
+ async function mapPool(items, limit, fn) {
224
+ const out = new Array(items.length);
225
+ let i = 0;
226
+ async function worker() {
227
+ while (i < items.length) {
228
+ const idx = i++;
229
+ try {
230
+ out[idx] = await fn(items[idx]);
231
+ } catch (err) {
232
+ console.warn(`[lqip] 外链抓取失败,跳过: ${items[idx]} — ${err.message}`);
233
+ }
234
+ }
235
+ }
236
+ await Promise.all(
237
+ Array.from({ length: Math.min(limit, items.length) }, () => worker()),
238
+ );
239
+ return out;
240
+ }
241
+
67
242
  try {
243
+ // public 图片:LQIP + 缩略图(照旧重算,public 内容变了要跟上)
68
244
  const files = collectImages(publicDir);
69
- const entries = await Promise.all(
70
- files.map(async (rel) => [
245
+ const lqipEntries = [];
246
+ const thumbEntries = [];
247
+ for (const rel of files) {
248
+ lqipEntries.push([
71
249
  `public:${rel}`,
72
250
  await sampleColors(path.join(publicDir, rel)),
73
- ]),
251
+ ]);
252
+ thumbEntries.push([`public:${rel}`, await makeThumb(rel)]);
253
+ }
254
+
255
+ // 外链:lqips.json 已有 url: 键即缓存,只抓缺失项
256
+ let cached = {};
257
+ if (!REFRESH) {
258
+ try {
259
+ cached = Object.fromEntries(
260
+ Object.entries(JSON.parse(fs.readFileSync(lqipFile, "utf8"))).filter(
261
+ ([k, v]) => k.startsWith("url:") && /^[0-9a-f]{18}$/i.test(v),
262
+ ),
263
+ );
264
+ } catch {
265
+ cached = {};
266
+ }
267
+ }
268
+ const remoteUrls = collectRemoteUrls();
269
+ const pending = remoteUrls.filter((u) => !(`url:${u}` in cached));
270
+ console.log(
271
+ `[lqip] 外链 ${remoteUrls.length} 条(缓存命中 ${remoteUrls.length - pending.length},待抓 ${pending.length})`,
74
272
  );
273
+ const fetched = await mapPool(pending, FETCH_CONCURRENCY, async (url) => [
274
+ url,
275
+ await fetchSample(url),
276
+ ]);
277
+ // 缓存命中的 url: 键原样合并(否则第二次运行会把它从产物中丢掉)
278
+ for (const [k, v] of Object.entries(cached)) lqipEntries.push([k, v]);
279
+ for (const pair of fetched) {
280
+ if (pair) lqipEntries.push([`url:${pair[0]}`, pair[1]]);
281
+ }
282
+
75
283
  fs.writeFileSync(
76
- outFile,
77
- JSON.stringify(Object.fromEntries(entries), null, 2) + "\n",
284
+ lqipFile,
285
+ JSON.stringify(Object.fromEntries(lqipEntries), null, 2) + "\n",
286
+ );
287
+ fs.writeFileSync(
288
+ thumbsFile,
289
+ JSON.stringify(Object.fromEntries(thumbEntries), null, 2) + "\n",
290
+ );
291
+ console.log(
292
+ `[lqip] public ${files.length} 张 + 外链 ${remoteUrls.length - pending.length + fetched.filter(Boolean).length} 条 → ${path.relative(cwd, lqipFile)} + ${path.relative(cwd, thumbsFile)}`,
78
293
  );
79
- console.log(`[lqip] ${files.length} 张图片 → ${path.relative(cwd, outFile)}`);
80
294
  } catch (err) {
81
295
  console.error("[lqip] 生成失败:", err);
82
296
  process.exit(1);