@namewta/skills-hub 0.1.47 → 0.1.49

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 (44) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.md +3 -3
  3. package/package.json +1 -1
  4. package/scripts/persistence/home.md +1 -0
  5. package/skills/dev/dev-archive/references/change-closure.md +4 -0
  6. package/skills/home/home-project-changelog/SKILL.md +5 -5
  7. package/skills/home/home-project-changelog/assets/project-changelog.md +7 -7
  8. package/skills/home/home-project-changelog/assets/worker-brief.md +1 -1
  9. package/skills/home/home-project-changelog/references/git-ranges.md +3 -0
  10. package/skills/home/home-project-changelog/references/tools.md +20 -2
  11. package/skills/home/home-project-changelog/references/workflow.md +5 -2
  12. package/skills/home/home-project-changelog/references/writing.md +20 -2
  13. package/skills/home/home-project-changelog/scripts/changelog.mjs +47 -5
  14. package/skills/home/home-project-changelog/scripts/contract.mjs +46 -2
  15. package/skills/home/home-project-changelog/scripts/git.mjs +15 -0
  16. package/skills/home/home-project-changelog/scripts/revision.mjs +231 -0
  17. package/skills/home/home-project-changelog/scripts/storage.mjs +32 -8
  18. package/skills/home/home-project-changelog/scripts/summary.mjs +17 -3
  19. package/skills/home/home-project-changelog/scripts/tasks.mjs +40 -0
  20. package/skills/home/home-setup/SKILL.md +1 -1
  21. package/skills/home/home-setup/references/registry.md +4 -0
  22. package/skills/home/home-setup/scripts/git.mjs +2 -0
  23. package/skills/home/home-website/SKILL.md +20 -0
  24. package/skills/home/home-website/assets/website/gitignore.tmpl +4 -0
  25. package/skills/home/home-website/assets/website/package-lock.json +2376 -0
  26. package/skills/home/home-website/assets/website/package.json +11 -0
  27. package/skills/home/home-website/assets/website/scripts/artifact.mjs +84 -0
  28. package/skills/home/home-website/assets/website/scripts/inputs.mjs +251 -0
  29. package/skills/home/home-website/assets/website/scripts/preview.mjs +50 -0
  30. package/skills/home/home-website/assets/website/scripts/render.mjs +97 -0
  31. package/skills/home/home-website/assets/website/scripts/site.mjs +173 -0
  32. package/skills/home/home-website/assets/website/site/.vitepress/theme/index.js +3 -0
  33. package/skills/home/home-website/assets/website/site/public/home-assets/app.js +262 -0
  34. package/skills/home/home-website/assets/website/site/public/home-assets/site.css +330 -0
  35. package/skills/home/home-website/assets/website/site/public/home-assets/start.js +7 -0
  36. package/skills/home/home-website/assets/website/site/templates/layout.mjs +93 -0
  37. package/skills/home/home-website/assets/website/site/templates/ledger.mjs +69 -0
  38. package/skills/home/home-website/assets/website/site/templates/model.mjs +104 -0
  39. package/skills/home/home-website/assets/website/site/templates/pages.mjs +75 -0
  40. package/skills/home/home-website/assets/website/site/templates/project-logs.mjs +130 -0
  41. package/skills/home/home-website/assets/website/site.config.json +6 -0
  42. package/skills/home/home-website/references/website.md +82 -0
  43. package/skills/home/home-website/scripts/init.mjs +57 -0
  44. package/skills/home/home-workflow/SKILL.md +1 -0
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "home-website",
3
+ "private": true,
4
+ "type": "module",
5
+ "engines": {"node": ">=22.14.0"},
6
+ "scripts": {
7
+ "build": "node scripts/site.mjs refresh",
8
+ "preview": "node scripts/site.mjs preview"
9
+ },
10
+ "devDependencies": {"vitepress": "1.6.4"}
11
+ }
@@ -0,0 +1,84 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { directory, read } from './inputs.mjs';
5
+
6
+ export function files(root, relative = '') {
7
+ const here = path.join(root,relative);
8
+ if (!directory(here)) throw Error('缺少目录:'+path.basename(here));
9
+ return fs.readdirSync(here,{withFileTypes:true}).sort((a,b) => a.name.localeCompare(b.name,'en')).flatMap(entry => {
10
+ const name = relative ? relative+'/'+entry.name : entry.name;
11
+ if (entry.isDirectory()) return files(root,name);
12
+ if (!entry.isFile()) throw Error('目录含非普通文件:'+name);
13
+ return [name];
14
+ });
15
+ }
16
+
17
+ export function fingerprint(website, model) {
18
+ const source = [...files(website,'scripts'),...files(website,'site'),'package.json','package-lock.json'];
19
+ const hash = createHash('sha256').update(JSON.stringify(model));
20
+ for (const name of source) {
21
+ const bytes = read(path.join(website,name));
22
+ if (!bytes) throw Error('缺少网站工程文件:'+name);
23
+ hash.update(JSON.stringify([name,createHash('sha256').update(bytes).digest('hex')]));
24
+ }
25
+ return hash.digest('hex');
26
+ }
27
+
28
+ export function manifest(root, names = files(root)) {
29
+ return names.map(name => {
30
+ const bytes = read(path.join(root,name));
31
+ if (!bytes) throw Error('制品在核对时发生变化:'+name);
32
+ return [name,createHash('sha256').update(bytes).digest('hex')];
33
+ });
34
+ }
35
+
36
+ const isOutputFile = name => /^(?:index\.html|404\.html|changelog\/index\.html|projects\/(?:index\.html|[a-z0-9][a-z0-9-]*\/(?:changelog\/)?index\.html)|data\/(?:catalog\.json|projects\/[a-z0-9][a-z0-9-]*\.json)|home-assets\/(?:app\.js|search-index\.js|start\.js|site\.css)|assets\/[A-Za-z0-9_./-]+\.(?:js|css|map|woff2?)|hashmap\.json|vp-icons\.css)$/u.test(name);
37
+
38
+ function publicPath(url,base) {
39
+ const [pathname,anchor] = url.split('#');
40
+ const name = pathname.slice(base.length);
41
+ return [!name || name.endsWith('/') ? name+'index.html' : name, anchor];
42
+ }
43
+
44
+ export function validateArtifact(candidate, base) {
45
+ const {dist,urls,expectedData,index} = candidate;
46
+ const output = files(dist);
47
+ const found = new Set(output);
48
+ const required = new Set([...urls,...expectedData.keys(),'home-assets/site.css','home-assets/app.js','home-assets/start.js']);
49
+ for (const name of output) {
50
+ if (!isOutputFile(name) || (/^(?:projects|data)\//u.test(name) && !required.has(name))) throw Error('静态制品含未声明文件:'+name);
51
+ }
52
+ for (const name of required) {
53
+ if (!found.has(name)) throw Error('静态制品缺少:'+name);
54
+ }
55
+ const bodies = new Map(urls.map(name => [name, fs.readFileSync(path.join(dist,name),'utf8')]));
56
+ const namedTargets = new Map();
57
+ for (const [name,html] of bodies) {
58
+ const ids = [...html.matchAll(/\sid="([^"]+)"/gu)].map(([,id]) => id);
59
+ const targets = new Set(ids);
60
+ if (targets.size !== ids.length) throw Error(name+' 含重复的页面锚点。');
61
+ namedTargets.set(name,targets);
62
+ }
63
+ const origin = 'http://localhost';
64
+ for (const [name, html] of bodies) {
65
+ if (!html.includes('class="home-site"') || !html.includes('id="main"')) throw Error(name+' 缺少服务器渲染的正文。');
66
+ for (const [,url] of html.matchAll(/\b(?:href|src)="([^"]+)"/gu)) {
67
+ const location = new URL(url, origin+base+name);
68
+ if (url.startsWith('//') || location.origin === origin && !location.pathname.startsWith(base)) {
69
+ throw Error(name+' 的链接超出站点前缀:'+url);
70
+ }
71
+ if (location.origin !== origin) continue;
72
+ const [target,anchor] = publicPath(location.pathname+location.hash,base);
73
+ if (!found.has(target) || (anchor && !namedTargets.get(target)?.has(anchor))) throw Error(name+' 中的链接无法定位:'+url);
74
+ }
75
+ }
76
+ for (const item of index) {
77
+ const [target,anchor] = publicPath(base+item.url,base);
78
+ if (!bodies.has(target) || (anchor && !namedTargets.get(target).has(anchor))) throw Error('搜索目标不存在:'+item.url);
79
+ }
80
+ for (const [name,expected] of expectedData) {
81
+ if (fs.readFileSync(path.join(dist,name),'utf8') !== expected) throw Error(name+' 的公开数据与本轮不一致。');
82
+ }
83
+ return output;
84
+ }
@@ -0,0 +1,251 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { parseMarkdown, validDay } from '../site/templates/project-logs.mjs';
5
+ import { statistics } from '../site/templates/model.mjs';
6
+
7
+ const idPattern = /^[a-z0-9][a-z0-9-]*$/u;
8
+ const plain = value => !!value && typeof value === 'object' && !Array.isArray(value);
9
+ const line = value => typeof value === 'string' && value.trim() && !/[\x00-\x1f\x7f]/u.test(value);
10
+ const decode = value => new TextDecoder('utf-8', { fatal: true }).decode(value);
11
+ const colors = ['amber', 'teal', 'blue', 'plum', 'coral', 'moss'];
12
+ const marks = ['layers', 'signal', 'code', 'folio', 'route', 'book'];
13
+
14
+ export function directory(filename) {
15
+ const stat = fs.lstatSync(filename, {throwIfNoEntry:false});
16
+ if (stat && !stat.isDirectory()) throw Error('须使用普通目录:' + path.basename(filename));
17
+ return !!stat;
18
+ }
19
+
20
+ export function read(filename) {
21
+ const stat = fs.lstatSync(filename, {throwIfNoEntry:false});
22
+ if (!stat) return null;
23
+ if (!stat.isFile()) throw Error('须使用普通文件:' + path.basename(filename));
24
+ const fd = fs.openSync(filename, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
25
+ try {
26
+ const opened = fs.fstatSync(fd);
27
+ // Windows Node 22 may report an unavailable volume identifier as zero from lstat.
28
+ const sameDevice = opened.dev === stat.dev || process.platform === 'win32' && (!opened.dev || !stat.dev);
29
+ if (!opened.isFile() || opened.ino !== stat.ino || !sameDevice) throw Error('读取期间输入发生变化:' + path.basename(filename));
30
+ return fs.readFileSync(fd);
31
+ } finally {
32
+ fs.closeSync(fd);
33
+ }
34
+ }
35
+
36
+ function checkKeys(value, allowed, label) {
37
+ if (!plain(value) || Object.keys(value).some(key => !allowed.includes(key))) throw Error(label + ' 含未知设置或格式错误。');
38
+ }
39
+
40
+ function https(value) {
41
+ if (!line(value)) throw Error('公开链接须为单行 HTTPS URL。');
42
+ const url = new URL(value);
43
+ if (url.protocol !== 'https:' || url.username || url.password) throw Error('公开链接须为没有凭据的 HTTPS URL。');
44
+ return url.href;
45
+ }
46
+
47
+ function config(value) {
48
+ checkKeys(value, ['title', 'base', 'scope', 'publicGroups', 'overrides'], 'site.config.json');
49
+ const {title, base, scope = 'all', publicGroups = [], overrides = {}} = value;
50
+ if (!line(title) || typeof base !== 'string' || !/^\/(?:[a-zA-Z0-9_-][a-zA-Z0-9._-]*\/)*$/u.test(base) || scope !== 'all') {
51
+ throw Error('设置需要 title、以 / 包围的 base、scope 为 all。');
52
+ }
53
+ if (!Array.isArray(publicGroups) || !publicGroups.every(line) || !plain(overrides)) throw Error('publicGroups 或 overrides 格式错误。');
54
+ const byId = new Map();
55
+ for (const [id, item] of Object.entries(overrides)) {
56
+ if (!idPattern.test(id)) throw Error('overrides 使用登记项目 ID。');
57
+ checkKeys(item, ['hidden','showChangelog','displayName','summary','docsUrl','repoUrl'], id);
58
+ for (const key of ['hidden','showChangelog']) {
59
+ if (Object.hasOwn(item,key) && typeof item[key] !== 'boolean') throw Error(id+' 的 '+key+' 应为布尔值。');
60
+ }
61
+ for (const key of ['displayName','summary']) {
62
+ if (Object.hasOwn(item,key) && !line(item[key])) throw Error(id+' 的 '+key+' 应为单行文字。');
63
+ }
64
+ byId.set(id, {...item, ...(item.docsUrl !== undefined ? {docsUrl:https(item.docsUrl)} : {}), ...(item.repoUrl !== undefined ? {repoUrl:https(item.repoUrl)} : {})});
65
+ }
66
+ return {title, base, publicGroups, byId};
67
+ }
68
+
69
+ function records(value) {
70
+ if (!plain(value) || ![1,2].includes(value.formatVersion) || !Array.isArray(value.repos)) throw Error('repos.json 只支持 v1/v2 的 repos 数组。');
71
+ const seen = new Set();
72
+ for (const repo of value.repos) {
73
+ if (!plain(repo) || typeof repo.id !== 'string' || !idPattern.test(repo.id) || seen.has(repo.id) || !line(repo.purpose)) {
74
+ throw Error('repos.json 含无效或重复的项目 ID,或缺少单行用途。');
75
+ }
76
+ if (repo.groups !== undefined && (!Array.isArray(repo.groups) || !repo.groups.every(line))) throw Error(repo.id+' 的登记分组格式错误。');
77
+ seen.add(repo.id);
78
+ }
79
+ return value.repos;
80
+ }
81
+
82
+ function readState(value) {
83
+ if (value === undefined) return {};
84
+ if (!plain(value) || value.formatVersion !== 1 || !plain(value.projects)) throw Error('changelogs/state.json 格式错误,请用 home-project-changelog 核对。');
85
+ for (const [id, project] of Object.entries(value.projects)) {
86
+ if (!idPattern.test(id) || !plain(project) || !plain(project.initialization) || !Array.isArray(project.ranges)
87
+ || project.lastSuccessfulRangeId !== (project.ranges.at(-1)?.rangeId ?? null)
88
+ || (Object.hasOwn(project,'pending') && !plain(project.pending))
89
+ || !project.ranges.length && !project.pending) {
90
+ throw Error('changelogs/state.json 中 '+id+' 的记录无效,请用 home-project-changelog 核对。');
91
+ }
92
+ const ids = new Set();
93
+ let previous = null;
94
+ for (const range of project.ranges) {
95
+ const dates = range?.displayDates;
96
+ const commits = range?.stats?.rangeCommitCount;
97
+ const head = range?.stats?.totalCommitCountAtHead;
98
+ const baseline = ['baseline','rebaseline'].includes(range?.kind);
99
+ if (!plain(range) || !line(range.rangeId) || ids.has(range.rangeId) || range.previousRangeId !== previous
100
+ || typeof range.savedAt !== 'string' || !Number.isFinite(Date.parse(range.savedAt))
101
+ || !['full-history','delta','baseline','rebaseline'].includes(range.kind)
102
+ || !plain(dates) || !validDay(dates.to) || (dates.from !== null && (!validDay(dates.from) || dates.from > dates.to))
103
+ || !Number.isSafeInteger(commits) || commits < 0 || (baseline && (dates.from !== null || commits !== 0))
104
+ || (head != null && (!Number.isSafeInteger(head) || head < commits))) {
105
+ throw Error('changelogs/state.json 中 '+id+' 的成功区间无效,请用 home-project-changelog 核对。');
106
+ }
107
+ ids.add(range.rangeId);
108
+ previous = range.rangeId;
109
+ }
110
+ }
111
+ return value.projects;
112
+ }
113
+
114
+ function publicText(value, privateValues) {
115
+ let text = value
116
+ .replace(/!?\[([^\]\n]*)\]\([^\n)]*\)/gu, '$1')
117
+ .replace(/^[ \t]*\[[^\]\n]+\]:[^\n]*$/gmu, '〔链接定义〕');
118
+ for (const hidden of privateValues) text = text.replaceAll(hidden, '〔本地资料〕');
119
+ return text.replace(/(?:https?:\/\/|git:\/\/|ssh:\/\/|file:\/\/|ftp:\/\/|mailto:|www\.)[^\s<>,。;、))]+/giu, '〔链接〕')
120
+ .replace(/[\w.-]+@[\w.-]+:[^\s<>,。;、]+/gu,'〔链接〕')
121
+ .replace(/(?:\b[A-Za-z]:[\\/]|(?:\.\.?[\\/])+|(?<![\p{L}\d/])\/(?=[\w.-]+\/)|\\\\(?=[\w.-]+\\))[^\s<>,。;、)]+/gu, '〔本地路径〕')
122
+ .replace(/[\u0000-\u0009\u000b-\u001f\u007f]/gu, ' ');
123
+ }
124
+
125
+ function savedPeriods(id, parsed, dated, saved, warnings) {
126
+ const blocks = parsed.periods.map((legacy,index) => ({legacy, dated:dated?.periods[index]}));
127
+ const oldest = [...blocks].reverse();
128
+ const bodyFor = (block, range) => range.ledger ? block.dated : block.legacy;
129
+ function matches(block, range) {
130
+ const period = bodyFor(block,range);
131
+ const {from,to} = range.displayDates;
132
+ const legacyStart = range.kind === 'full-history' && from === null;
133
+ const baseline = range.kind === 'baseline' || range.kind === 'rebaseline';
134
+ return period.verified && period.to === to && (legacyStart || period.from === from)
135
+ && period.commits === range.stats.rangeCommitCount && period.baseline === baseline;
136
+ }
137
+ function ordered(ranges, periods) {
138
+ const found = [];
139
+ let index = 0;
140
+ for (const range of ranges) {
141
+ while (index < periods.length && !matches(periods[index],range)) index += 1;
142
+ if (index === periods.length) throw Error(id+' 的成功区间无法核对 Markdown 日期、提交数或统计:'+range.displayDates.to+'。');
143
+ found.push(periods[index++]);
144
+ }
145
+ return found;
146
+ }
147
+ // 两个方向分别找最早和最晚的配对。两者都相同时,已保存区间的有序配对才唯一。
148
+ const forward = ordered(saved.ranges,oldest);
149
+ const backward = ordered([...saved.ranges].reverse(),blocks).reverse();
150
+ if (forward.some((period,index) => period !== backward[index])) throw Error(id+' 的成功区间与 Markdown 有多种配对,请先核对原文。');
151
+ if (forward.length !== parsed.periods.length) warnings.push(id+' 有未匹配的日期段,保留在 Home。');
152
+ if (parsed.legacy) warnings.push(id+' 含历史补记,保留在单仓页。');
153
+ const paired = forward.map((block,index) => ({period:bodyFor(block,saved.ranges[index]),range:saved.ranges[index]}));
154
+ for (const {period} of paired) {
155
+ if (period.notes.some(note => /^### |^[-*+] /u.test(note))) warnings.push(id+' '+period.key+' 含额外正文,保留在区间说明。');
156
+ }
157
+ return paired.reverse();
158
+ }
159
+
160
+ function publicPeriod(id, period, range, text) {
161
+ const { ledger } = range;
162
+ let items, commitMonths;
163
+ if (ledger === undefined) {
164
+ items = period.items.map(([category, value, markers]) => [category, text(value), markers]);
165
+ } else {
166
+ const fail = () => { throw Error(id+' 的任务明细与成功记录不一致,请用 home-project-changelog 修订该区间。'); };
167
+ if (ledger?.version !== 1 || !plain(ledger.commitMonths) || !Array.isArray(ledger.tasks)
168
+ || ledger.tasks.length !== period.items.length) fail();
169
+ commitMonths = {};
170
+ let total = 0;
171
+ for (const [month,count] of Object.entries(ledger.commitMonths)) {
172
+ if (!validDay(month+'-01') || !Number.isSafeInteger(count) || count <= 0) fail();
173
+ total += count;
174
+ commitMonths[month] = count;
175
+ }
176
+ if (total !== period.commits) fail();
177
+ const ids = new Set();
178
+ items = period.items.map(([category,value,markers,meta],index) => {
179
+ const task = ledger.tasks[index];
180
+ if (!plain(task) || typeof task.id !== 'string' || !/^task-[0-9a-f]{16}$/u.test(task.id) || ids.has(task.id)
181
+ || !validDay(task.date) || !commitMonths[task.date.slice(0,7)] || task.date !== meta?.date
182
+ || task.area !== meta.area || (task.area !== null && !line(task.area))
183
+ || task.category !== category || task.text !== value || JSON.stringify(task.markers) !== JSON.stringify(markers)) fail();
184
+ ids.add(task.id);
185
+ return [category,text(value),markers,{id:task.id,date:task.date,area:task.area && text(task.area)}];
186
+ });
187
+ const features = ledger.tasks.filter(task => task.category === '功能');
188
+ const added = features.every(task => typeof task.added === 'boolean') ? features.filter(task => task.added).length : null;
189
+ if (period.added !== added) fail();
190
+ }
191
+ const notes = period.notes.map(text);
192
+ return {...period,items,notes,note:notes.join('\n'),commitMonths};
193
+ }
194
+
195
+ export function inputs(website) {
196
+ const home = path.dirname(website);
197
+ const sources = [];
198
+ function take(filename, required = false) {
199
+ const bytes = read(filename);
200
+ if (required && !bytes) {
201
+ if (filename.endsWith('repos.json')) throw Error('缺少 repos.json,请先通过 home-setup 登记项目。');
202
+ throw Error('缺少 '+path.basename(filename)+'。');
203
+ }
204
+ sources.push([filename,bytes ? createHash('sha256').update(bytes).digest('hex') : null]);
205
+ return bytes;
206
+ }
207
+ const parse = (bytes, name) => {
208
+ try { return JSON.parse(decode(bytes)); } catch { throw Error(name+' 无法读取为 UTF-8 JSON。'); }
209
+ };
210
+ const settings = config(parse(take(path.join(website,'site.config.json'),true),'site.config.json'));
211
+ const registered = records(parse(take(path.join(home,'repos.json'),true),'repos.json'));
212
+ const logs = path.join(home,'changelogs');
213
+ directory(logs);
214
+ const stateBytes = take(path.join(logs,'state.json'));
215
+ const state = readState(stateBytes ? parse(stateBytes,'state.json') : undefined);
216
+ const warnings = [], excluded = [];
217
+ const privateValues = [...new Set(registered.flatMap(repo => [
218
+ repo.localPath, repo.remote, repo.backgroundRef,
219
+ ...(Array.isArray(repo.remotes) ? repo.remotes.flatMap(remote => [...(remote?.urls ?? []), ...(remote?.pushUrls ?? [])]) : []),
220
+ ]).filter(value => typeof value === 'string' && value.length >= 3))].sort((a,b) => b.length-a.length);
221
+ const text = value => publicText(value, privateValues);
222
+ const projects = [];
223
+ for (const repo of registered) {
224
+ const {id} = repo;
225
+ const override = settings.byId.get(id) ?? {};
226
+ if (override.hidden) { excluded.push({id, reason:'hidden'}); continue; }
227
+ if (override.showChangelog === false) { excluded.push({id,reason:'changelog-disabled'}); continue; }
228
+ const saved = Object.hasOwn(state,id) ? state[id] : undefined;
229
+ if (!saved) { excluded.push({id,reason:'no-state'}); continue; }
230
+ if (saved.pending) throw Error(id+' 的日志有待确认写入,请先用 home-project-changelog 恢复。');
231
+ const bytes = take(path.join(logs,id+'.md'));
232
+ if (!bytes) throw Error(id+' 的日志正文缺失,请先恢复 Markdown。');
233
+ let body;
234
+ try { body = decode(bytes); } catch { throw Error(id+' 的日志正文需要可读的 UTF-8 Markdown。'); }
235
+ const dated = saved.ranges.some(range=>range.ledger) ? parseMarkdown(body,{datedOnly:true}) : null;
236
+ const parsed = saved.ranges.some(range=>!range.ledger) ? parseMarkdown(body) : dated;
237
+ const periods = savedPeriods(id,parsed,dated,saved,warnings).map(({period,range}) => publicPeriod(id,period,range,text));
238
+ const index = projects.length;
239
+ projects.push({
240
+ id, name:text(override.displayName ?? id), purpose:text(override.summary ?? repo.purpose),
241
+ groups:(repo.groups ?? []).filter(group => settings.publicGroups.includes(group)).map(text),
242
+ color:colors[index % colors.length], mark:marks[index % marks.length], repoUrl:override.repoUrl, docsUrl:override.docsUrl,
243
+ periods, stats:statistics(periods), headCommits:saved.ranges.at(-1).stats.totalCommitCountAtHead ?? null,
244
+ legacy:text(parsed.legacy),
245
+ });
246
+ }
247
+ return {
248
+ model:{title:text(settings.title),base:settings.base,projects},
249
+ inputRevision:JSON.stringify(sources), hasState:Boolean(stateBytes), warnings, excluded
250
+ };
251
+ }
@@ -0,0 +1,50 @@
1
+ import http from 'node:http';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ const types = {
6
+ '.html':'text/html; charset=utf-8', '.css':'text/css; charset=utf-8',
7
+ '.js':'text/javascript; charset=utf-8', '.json':'application/json; charset=utf-8',
8
+ '.woff':'font/woff', '.woff2':'font/woff2',
9
+ };
10
+
11
+ export function preview(dist,base,value) {
12
+ if (!/^\d+$/u.test(value) || Number(value) > 65535) throw Error('端口须为 0 至 65535 的整数。');
13
+ const server = http.createServer((request,response) => {
14
+ if (!['GET','HEAD'].includes(request.method)) {
15
+ response.writeHead(405,{Allow:'GET, HEAD'}).end();
16
+ return;
17
+ }
18
+ const url = new URL(request.url,'http://localhost');
19
+ const address = url.pathname;
20
+ if (base !== '/' && (address === '/' || address === base.slice(0,-1))) {
21
+ response.writeHead(302,{Location:base+url.search}).end();
22
+ return;
23
+ }
24
+ const relative = address.startsWith(base) ? address.slice(base.length) : null;
25
+ const valid = relative !== null && /^[a-zA-Z0-9_./-]*$/u.test(relative)
26
+ && relative.split('/').every(segment => !segment.startsWith('.'));
27
+ let file = valid ? path.join(dist, !relative || relative.endsWith('/') ? relative+'index.html' : relative) : null;
28
+ if (file && fs.lstatSync(file,{throwIfNoEntry:false})?.isDirectory()) {
29
+ response.writeHead(308,{Location:address+'/'+url.search}).end();
30
+ return;
31
+ }
32
+ if (file && !path.extname(file)) file += '.html';
33
+ const exists = file && fs.lstatSync(file,{throwIfNoEntry:false})?.isFile() && types[path.extname(file)];
34
+ if (!exists) file = path.join(dist,'404.html');
35
+ const stat = fs.lstatSync(file,{throwIfNoEntry:false});
36
+ if (!stat?.isFile()) { response.writeHead(404).end(); return; }
37
+ response.writeHead(exists ? 200 : 404, {
38
+ 'Content-Type':types[path.extname(file)],
39
+ 'Content-Length':stat.size,
40
+ 'Cache-Control':'no-store',
41
+ });
42
+ if (request.method === 'HEAD') response.end();
43
+ else fs.createReadStream(file).on('error',()=>response.destroy()).pipe(response);
44
+ });
45
+ server.on('error',error => {
46
+ console.error('预览启动失败:'+error.message);
47
+ process.exitCode = 1;
48
+ });
49
+ server.listen(Number(value),'127.0.0.1',() => console.log('http://127.0.0.1:'+server.address().port+base));
50
+ }
@@ -0,0 +1,97 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { frame, logPath, projectPath } from '../site/templates/layout.mjs';
4
+ import { activityMonths, itemId, observationWindows, periodTitle, rangeLabel, statistics } from '../site/templates/model.mjs';
5
+ import { overview, catalog, detail, repositoryLog } from '../site/templates/pages.mjs';
6
+ import { changelog } from '../site/templates/ledger.mjs';
7
+ import { publicProject } from '../site/templates/project-logs.mjs';
8
+
9
+ const json = value => JSON.stringify(value, null, 2) + '\n';
10
+
11
+ function transformHtml(html, page, base, notFound) {
12
+ // The HTTP server may return the 404 page at a URL of any depth.
13
+ if (page === '404.md') return html.replace('<div id="app"></div>', () => notFound);
14
+ const depth = page.split('/').length - 1;
15
+ const relativeRoot = '../'.repeat(depth) || './';
16
+ return html.replace(/(<(?:link|script)\b[^>]*?\s(?:href|src)=")(\/[^"#?]+)"/gu, (tag, attribute, url) =>
17
+ url.startsWith(base) && !url.startsWith('//') ? attribute + relativeRoot + url.slice(base.length) + '"' : tag);
18
+ }
19
+
20
+ export function render(website, run, model) {
21
+ const {title,base,projects} = model;
22
+ const windows = observationWindows(projects);
23
+ const stats = statistics(projects.flatMap(project => project.periods));
24
+ const source = path.join(run,'src');
25
+ const dist = path.join(run,'dist');
26
+ fs.cpSync(path.join(website,'site/.vitepress'),path.join(source,'.vitepress'),{recursive:true});
27
+ fs.cpSync(path.join(website,'site/public'),path.join(source,'public'),{recursive:true});
28
+ const shape = {
29
+ title, base, outDir:dist, lang:'zh-CN', cleanUrls:true, appearance:false, lastUpdated:false, mpa:true,
30
+ head:[
31
+ ['link',{rel:'icon',href:'data:,'}],
32
+ ['link',{rel:'stylesheet',href:base+'home-assets/site.css'}],
33
+ ['script',{src:base+'home-assets/start.js'}],
34
+ ['script',{defer:'',src:base+'home-assets/search-index.js'}],
35
+ ['script',{defer:'',src:base+'home-assets/app.js'}],
36
+ ]
37
+ };
38
+ // VitePress reserves 404.md and emits an empty app shell for it.
39
+ const notFound = frame({base,title,section:'',content:'<h1>页面不存在</h1><p><a href="'+base+'">返回项目总览</a></p>'});
40
+ fs.writeFileSync(path.join(source,'.vitepress/config.mjs'),
41
+ 'const config = '+json(shape)
42
+ +transformHtml.toString()+'\n'
43
+ +'config.transformHtml = (html, _filename, {page}) => transformHtml(html, page, config.base, '+JSON.stringify(notFound)+');\n'
44
+ +'export default config;\n');
45
+ const urls = [];
46
+ function write(relative,data) {
47
+ const filename = path.join(source,relative);
48
+ fs.mkdirSync(path.dirname(filename),{recursive:true});
49
+ fs.writeFileSync(filename,data);
50
+ }
51
+ function page(route, pageTitle, section, content) {
52
+ const stem = route.endsWith('/') || !route ? route+'index' : route;
53
+ const name = path.posix.basename(stem);
54
+ const markup = frame({base,title,section,content});
55
+ // Only markup from the controlled renderers enters Vue. Source text is already escaped.
56
+ write(stem+'.content.json',json({markup}));
57
+ write(stem+'.md','---\n'+JSON.stringify({title:pageTitle})+'\n---\n\n'
58
+ +'<script setup>\nimport page from "./'+name+'.content.json";\n</script>\n\n<div v-html="page.markup"></div>\n');
59
+ urls.push(stem+'.html');
60
+ }
61
+ page('',title,'home',overview(base,projects,windows,stats));
62
+ page('projects/','项目目录','projects',catalog(base,projects));
63
+ page('changelog/','变更时间线','changelog',changelog(base,projects,windows,stats));
64
+ urls.push('404.html');
65
+ const index = [];
66
+ const catalogData = {schemaVersion:2,stats,projects:[],months:activityMonths(projects).map(({key,changes,commits,groups}) => ({
67
+ month:key === 'undated' ? null : key,changes,commits,
68
+ projects:groups.map(({project,commits,rows}) => ({id:project.id,commits,changes:rows.filter(row=>row.index >= 0).length})),
69
+ })),windows:windows.map(({from,to,groups,rangeCount,stats}) => ({
70
+ from, to, projects:groups.map(({project}) => project.id), rangeCount, stats,
71
+ }))};
72
+ const expectedData = new Map();
73
+ for (const project of projects) {
74
+ const {id,name,purpose,groups,periods,legacy} = project;
75
+ const data = 'projects/'+id+'.json';
76
+ const projected = publicProject(project);
77
+ page(projectPath(project),name,'projects',detail(base,project,projected.stats));
78
+ index.push({kind:'项目',name,id,title:name,text:purpose,group:groups.join(' '),url:projectPath(project)});
79
+ page(logPath(project),name+' 变更日志','projects',repositoryLog(base,project,projected.stats));
80
+ for (const period of periods) {
81
+ const date = rangeLabel(period);
82
+ if (!period.items.length) index.push({kind:'区间',name,id,title:periodTitle(period),text:period.note,date,url:logPath(project,period)});
83
+ period.items.forEach(([category,text,markers,meta],i) => {
84
+ index.push({kind:'变更',name,id,title:text,text:[category,meta?.area,...markers].filter(Boolean).join(' · '),
85
+ date:meta?.date ?? date,url:logPath(project)+'#'+itemId(period,i)});
86
+ });
87
+ }
88
+ if (legacy) index.push({kind:'补记',name,id,title:'历史补记',text:legacy,url:logPath(project)+'#legacy'});
89
+ expectedData.set('data/'+data,json(projected));
90
+ catalogData.projects.push({id,name,purpose,ranges:periods.length,entries:projected.stats.changes,
91
+ commits:projected.stats.commits,headCommits:project.headCommits,data});
92
+ }
93
+ expectedData.set('data/catalog.json',json(catalogData));
94
+ expectedData.set('home-assets/search-index.js','window.homeSearchIndex = '+JSON.stringify(index).replaceAll('<','\\u003c')+';\n');
95
+ for (const [name,bytes] of expectedData) write('public/'+name,bytes);
96
+ return {source,dist,urls,expectedData,index};
97
+ }