@horizonwing/engine 0.0.0-stage → 0.1.1

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 (53) hide show
  1. package/README.md +32 -2
  2. package/drizzle/pg/schema.ts +100 -0
  3. package/drizzle/postgres/0000_smooth_princess_powerful.sql +34 -0
  4. package/drizzle/postgres/0001_colossal_morbius.sql +50 -0
  5. package/drizzle/postgres/README.md +23 -0
  6. package/drizzle/postgres/meta/0000_snapshot.json +244 -0
  7. package/drizzle/postgres/meta/0001_snapshot.json +545 -0
  8. package/drizzle/postgres/meta/_journal.json +20 -0
  9. package/drizzle/schema.ts +128 -0
  10. package/drizzle/sqlite/0000_cooing_jackpot.sql +34 -0
  11. package/drizzle/sqlite/0001_living_ben_urich.sql +49 -0
  12. package/drizzle/sqlite/meta/0000_snapshot.json +231 -0
  13. package/drizzle/sqlite/meta/0001_snapshot.json +554 -0
  14. package/drizzle/sqlite/meta/_journal.json +20 -0
  15. package/package.json +80 -4
  16. package/src/account-pages.tsx +152 -0
  17. package/src/auth.tsx +265 -0
  18. package/src/cache.ts +199 -0
  19. package/src/content.ts +448 -0
  20. package/src/db.ts +107 -0
  21. package/src/feeds.ts +376 -0
  22. package/src/guard.ts +126 -0
  23. package/src/html.ts +20 -0
  24. package/src/i18n.ts +304 -0
  25. package/src/index.ts +27 -0
  26. package/src/md.ts +278 -0
  27. package/src/media.ts +70 -0
  28. package/src/password.ts +59 -0
  29. package/src/platform.node.ts +98 -0
  30. package/src/platform.postgres.ts +61 -0
  31. package/src/platform.shared.ts +114 -0
  32. package/src/platform.ts +24 -0
  33. package/src/platform.workers.ts +94 -0
  34. package/src/ratelimit.ts +144 -0
  35. package/src/section.ts +123 -0
  36. package/src/sections/blog/index.tsx +93 -0
  37. package/src/sections/blog/schema.ts +12 -0
  38. package/src/sections/blog/views/pages.tsx +167 -0
  39. package/src/sections/docs/index.tsx +67 -0
  40. package/src/sections/docs/schema.ts +16 -0
  41. package/src/sections/docs/views/pages.tsx +181 -0
  42. package/src/sections/landing/index.tsx +42 -0
  43. package/src/sections/landing/views/pages.tsx +218 -0
  44. package/src/seo.ts +193 -0
  45. package/src/server.ts +122 -0
  46. package/src/services/content.ts +342 -0
  47. package/src/turnstile.ts +62 -0
  48. package/src/types.ts +192 -0
  49. package/src/views/error.tsx +36 -0
  50. package/src/views/index.tsx +13 -0
  51. package/src/views/layout.tsx +89 -0
  52. package/themes/warm/tokens.css +119 -0
  53. package/tsconfig.json +32 -0
package/src/content.ts ADDED
@@ -0,0 +1,448 @@
1
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { join, sep } from 'node:path';
3
+ import { parse as parseYaml } from 'yaml';
4
+ import { z, type ZodType } from 'zod';
5
+ import { RENDERER_VERSION, renderMarkdown } from './md';
6
+ import type { AppDatabase } from './db';
7
+ import type { Platform } from './types';
8
+ import {
9
+ upsertContentRows,
10
+ upsertRedirects,
11
+ removeContentSlugs,
12
+ removeRedirectsNotIn,
13
+ listSectionChecksums,
14
+ } from './services/content';
15
+ import type { ContentUpsert, RedirectUpsert } from './services/content';
16
+
17
+ /**
18
+ * 内容引擎(总设计 §4):repo markdown → frontmatter 解析 → zod 校验 →
19
+ * checksum → 与库 diff → 受控 batch upsert → content_version 写 kv。
20
+ *
21
+ * 本文件是离线同步管线(scripts/sync-content.ts 调用),不进 workers 运行时
22
+ * (node:fs / node 侧 crypto);workers 侧运行时只经 services/content.ts 读库。
23
+ */
24
+
25
+ /* ------------------------------------------------------------------ frontmatter */
26
+
27
+ /**
28
+ * 日期字段:yaml 包会把 ISO 日期解析成 Date 实例,也可能以字符串/数字到达
29
+ * (z.coerce.date() 在 zod v4 下不收 Date 入参,这里显式 preprocess 归一)。
30
+ */
31
+ const dateField = z.preprocess(
32
+ (v) => {
33
+ if (v instanceof Date) return Number.isNaN(v.getTime()) ? v : v;
34
+ if (typeof v === 'string' || typeof v === 'number') {
35
+ const d = new Date(v);
36
+ return Number.isNaN(d.getTime()) ? v : d;
37
+ }
38
+ return v;
39
+ },
40
+ z.date(),
41
+ );
42
+
43
+ /**
44
+ * 基础 Frontmatter schema:title/description/date 必填,其余可选;多余字段进 meta。
45
+ *
46
+ * date 必填(M2 前置小修,implement.md 步骤 0):缺 date 时同步管线回退「同步时刻」,
47
+ * checksum 每次同步都变化 → content_version 每次翻新 → 全站 SWR 缓存键被隐形打翻。
48
+ */
49
+ export const frontmatterSchema = z.looseObject({
50
+ title: z.string().trim().min(1).max(200),
51
+ description: z.string().trim().min(1).max(500),
52
+ date: dateField,
53
+ updated: dateField.optional(),
54
+ tags: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
55
+ draft: z.boolean().optional(),
56
+ author: z.string().trim().max(120).optional(),
57
+ /** M3 起多值;M1 固定 zh-CN */
58
+ locale: z.string().trim().max(20).optional(),
59
+ /** slug 变更后的旧地址('old-slug' 或 '/blog/old-slug',可数组) */
60
+ redirect_from: z.union([z.string(), z.array(z.string())]).optional(),
61
+ });
62
+
63
+ export type Frontmatter = z.infer<typeof frontmatterSchema>;
64
+
65
+ /**
66
+ * 栏目 frontmatter 已知键 = schema 自身 shape(栏目 schema 可 extend 出
67
+ * order/group 等字段);shape 之外的键进 meta(总设计 §4:meta = 剩余 frontmatter)。
68
+ */
69
+ function knownKeysOf(schema: ZodType): Set<string> {
70
+ const shape = (schema as unknown as { shape?: Record<string, unknown> }).shape;
71
+ return new Set(shape ? Object.keys(shape) : []);
72
+ }
73
+
74
+ export class ContentValidationError extends Error {
75
+ issues: string[];
76
+ constructor(issues: string[]) {
77
+ super(`frontmatter 校验失败:\n - ${issues.join('\n - ')}`);
78
+ this.name = 'ContentValidationError';
79
+ this.issues = issues;
80
+ }
81
+ }
82
+
83
+ /** `---` 围栏切分(标准 frontmatter 语义:首个闭合围栏前为 fm) */
84
+ export function splitFrontmatter(raw: string): { fmRaw: string; body: string } {
85
+ const normalized = raw.replace(/\r\n?/g, '\n');
86
+ const m = /^---[ \t]*\n([\s\S]*?)\n---[ \t]*(?:\n([\s\S]*))?$/.exec(normalized);
87
+ if (!m) throw new ContentValidationError(['缺少 `---` 围栏 frontmatter(文件需以 --- 开头)']);
88
+ return { fmRaw: m[1] ?? '', body: (m[2] ?? '').replace(/^\n+/, '') };
89
+ }
90
+
91
+ /**
92
+ * frontmatter 解析 + zod 校验;返回规范化 fm 与剩余 meta。
93
+ * schema 缺省用基础 frontmatterSchema;栏目可传自己的 schema(shape 外的键进 meta)。
94
+ */
95
+ export function parseFrontmatter(fmRaw: string, schema: ZodType = frontmatterSchema): { fm: Frontmatter; meta: Record<string, unknown> } {
96
+ let raw: unknown;
97
+ try {
98
+ raw = parseYaml(fmRaw);
99
+ } catch (err) {
100
+ throw new ContentValidationError([`YAML 解析失败: ${(err as Error).message}`]);
101
+ }
102
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
103
+ throw new ContentValidationError(['frontmatter 必须是 YAML 映射']);
104
+ }
105
+ const known = knownKeysOf(schema);
106
+ const parsed = schema.safeParse(raw);
107
+ if (!parsed.success) {
108
+ throw new ContentValidationError(parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`));
109
+ }
110
+ const meta: Record<string, unknown> = {};
111
+ for (const [k, v] of Object.entries(parsed.data as Record<string, unknown>)) {
112
+ if (!known.has(k)) meta[k] = v;
113
+ }
114
+ return { fm: parsed.data as Frontmatter, meta };
115
+ }
116
+
117
+ /* ------------------------------------------------------------------ 文件模型 */
118
+
119
+ export interface ContentFile {
120
+ section: string;
121
+ slug: string;
122
+ locale: string;
123
+ title: string;
124
+ description: string;
125
+ publishedAt: Date;
126
+ updatedAt: Date;
127
+ tags: string[];
128
+ draft: boolean;
129
+ author: string | null;
130
+ redirectFrom: string[];
131
+ meta: Record<string, unknown>;
132
+ bodyMd: string;
133
+ /** 同步期渲染产物(校验时已成功渲染,坏内容不进库) */
134
+ bodyHtml: string;
135
+ rendererVersion: string;
136
+ checksum: string;
137
+ }
138
+
139
+ const SLUG_RE = /^[a-z0-9][a-z0-9/_-]*$/i;
140
+
141
+ /**
142
+ * WebCrypto sha256(node 20+ 与 workers 都有 globalThis.crypto.subtle,
143
+ * 同步管线与将来可能的 workers 侧复用同一实现)。
144
+ */
145
+ export async function sha256Hex(input: string): Promise<string> {
146
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));
147
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
148
+ }
149
+
150
+ /** checksum = sha256(规范 fm JSON + body):fm 或正文任一变化都会翻新 */
151
+ export async function computeChecksum(parts: { title: string; description: string; date: string; updated: string; tags: string[]; draft: boolean; author: string | null; locale: string; meta: Record<string, unknown>; body: string }): Promise<string> {
152
+ const canonical = JSON.stringify([
153
+ parts.title, parts.description, parts.date, parts.updated, parts.tags, parts.draft, parts.author, parts.locale, parts.meta,
154
+ ]);
155
+ return sha256Hex(`${canonical}\n---\n${parts.body}`);
156
+ }
157
+
158
+ /**
159
+ * 单文件解析:section/slug 来自目录结构(content/<section>/<slug>.md,
160
+ * docs 支持嵌套目录),frontmatter 必须过 zod(schema 缺省基础版,栏目可传
161
+ * 自己的 schema),渲染失败立即抛(部署期 fail-fast)。
162
+ */
163
+ export async function parseContentFile(section: string, relPath: string, raw: string, fallbackNow: number, schema?: ZodType, locales?: string[]): Promise<ContentFile> {
164
+ if (!relPath.endsWith('.md')) throw new ContentValidationError([`${section}/${relPath}: 只支持 .md`]);
165
+ // locale 目录约定:content/<section>/<locale>/<slug>.md(M3);未传 locales 维持 M1 行为
166
+ const resolved = resolveContentLocale(relPath.slice(0, -3), locales);
167
+ const slug = resolved.slugPath.split(sep).join('/');
168
+ if (!SLUG_RE.test(slug)) {
169
+ throw new ContentValidationError([`${section}/${relPath}: slug 不合法(${slug}),仅允许字母数字/-_`]);
170
+ }
171
+
172
+ const { fmRaw, body } = splitFrontmatter(raw);
173
+ const { fm, meta } = parseFrontmatter(fmRaw, schema ?? frontmatterSchema);
174
+ // 目录约定优先(URL 即事实源);frontmatter locale 仅在无 locales 清单时兜底
175
+ const locale = locales && locales.length > 0 ? resolved.locale : (fm.locale ?? 'zh-CN');
176
+ // date 必填(schema 校验已保证);updated 缺省同 date
177
+ const dateStr = fm.date.toISOString();
178
+ const updatedStr = (fm.updated ?? fm.date).toISOString();
179
+
180
+ const checksum = await computeChecksum({
181
+ title: fm.title,
182
+ description: fm.description,
183
+ date: dateStr,
184
+ updated: updatedStr,
185
+ tags: fm.tags ?? [],
186
+ draft: fm.draft ?? false,
187
+ author: fm.author ?? null,
188
+ locale,
189
+ meta,
190
+ body,
191
+ });
192
+
193
+ // 同步期就渲染:校验不过 = 部署期 throw,坏内容永远不进库
194
+ let bodyHtml: string;
195
+ try {
196
+ bodyHtml = renderMarkdown(body);
197
+ } catch (err) {
198
+ throw new ContentValidationError([`${section}/${slug}: markdown 渲染失败 ${(err as Error).message}`]);
199
+ }
200
+
201
+ const redirectFrom = (Array.isArray(fm.redirect_from) ? fm.redirect_from : fm.redirect_from ? [fm.redirect_from] : [])
202
+ .map((v) => normalizeFromPath(v, section, locale, locales))
203
+ .filter((v): v is string => v.length > 0);
204
+
205
+ return {
206
+ section,
207
+ slug,
208
+ locale,
209
+ title: fm.title,
210
+ description: fm.description,
211
+ publishedAt: new Date(dateStr),
212
+ updatedAt: new Date(updatedStr),
213
+ tags: fm.tags ?? [],
214
+ draft: fm.draft ?? false,
215
+ author: fm.author ?? null,
216
+ redirectFrom,
217
+ meta,
218
+ bodyMd: body,
219
+ bodyHtml,
220
+ rendererVersion: RENDERER_VERSION,
221
+ checksum,
222
+ };
223
+ }
224
+
225
+ /** redirect_from 归一:'old-slug' → '/blog/old-slug';'/blog/old' 原样。
226
+ * variant locale 的内容带 locale 前缀('/en/blog/old-slug')。 */
227
+ export function normalizeFromPath(value: string, section: string, locale?: string, locales?: string[]): string {
228
+ const t = value.trim().replace(/\/+$/, '');
229
+ if (!t) return '';
230
+ if (t.startsWith('/')) return t;
231
+ const bare = `/${section}/${t.replace(/^\.?\//, '')}`;
232
+ const base = locales?.[0];
233
+ if (locale && locales && base && locale !== base && locales.includes(locale)) {
234
+ return `/${locale}${bare}`;
235
+ }
236
+ return bare;
237
+ }
238
+
239
+ /**
240
+ * locale 目录约定(M3):relPath 首段 ∈ locales → 该段是 locale,余下是 slug
241
+ * ('en/hello.md' → locale 'en', slug 'hello');否则 baseLocale。
242
+ * 未传 locales(M1/M2 兼容)= 全部按 baseLocale,slug 含完整 relPath。
243
+ */
244
+ export function resolveContentLocale(relPath: string, locales?: string[]): { locale: string; slugPath: string } {
245
+ if (locales && locales.length > 0) {
246
+ const m = /^([^/]+)\//.exec(relPath);
247
+ const first = m?.[1];
248
+ if (first && locales.includes(first)) {
249
+ return { locale: first, slugPath: relPath.slice(first.length + 1) };
250
+ }
251
+ }
252
+ return { locale: locales?.[0] ?? 'zh-CN', slugPath: relPath };
253
+ }
254
+
255
+ export function toUpsert(file: ContentFile, bodyHtml: string): ContentUpsert {
256
+ return {
257
+ section: file.section,
258
+ slug: file.slug,
259
+ locale: file.locale,
260
+ title: file.title,
261
+ description: file.description,
262
+ publishedAt: file.publishedAt,
263
+ updatedAt: file.updatedAt,
264
+ tags: file.tags,
265
+ meta: file.meta,
266
+ bodyMd: file.bodyMd,
267
+ bodyHtml,
268
+ rendererVersion: RENDERER_VERSION,
269
+ checksum: file.checksum,
270
+ draft: file.draft,
271
+ author: file.author,
272
+ };
273
+ }
274
+
275
+ /* ------------------------------------------------------------------ 目录扫描 */
276
+
277
+ /**
278
+ * 扫描 content/<section>/ 下全部 .md(递归,docs 嵌套目录 → 嵌套 slug)。
279
+ * 跳过下划线开头的目录/文件(约定:_drafts 等不入库)。
280
+ */
281
+ export function scanContentDir(contentDir: string, sections: string[]): { section: string; relPath: string; raw: string }[] {
282
+ const out: { section: string; relPath: string; raw: string }[] = [];
283
+ for (const section of sections) {
284
+ const dir = join(contentDir, section);
285
+ let walk: (base: string, prefix: string) => void;
286
+ walk = (base: string, prefix: string) => {
287
+ let entries: string[];
288
+ try {
289
+ entries = readdirSync(base);
290
+ } catch {
291
+ return; // 栏目目录不存在视为空
292
+ }
293
+ for (const name of entries.sort()) {
294
+ if (name.startsWith('_') || name.startsWith('.')) continue;
295
+ const full = join(base, name);
296
+ const rel = prefix ? `${prefix}/${name}` : name;
297
+ if (statSync(full).isDirectory()) {
298
+ walk(full, rel);
299
+ } else if (name.endsWith('.md')) {
300
+ out.push({ section, relPath: rel, raw: readFileSync(full, 'utf8') });
301
+ }
302
+ }
303
+ };
304
+ walk(dir, '');
305
+ }
306
+ return out;
307
+ }
308
+
309
+ /** content/ 目录下的栏目名(目录存在即栏目;下划线/点开头跳过) */
310
+ export function scanSectionNames(contentDir: string): string[] {
311
+ let entries: string[];
312
+ try {
313
+ entries = readdirSync(contentDir);
314
+ } catch {
315
+ return [];
316
+ }
317
+ return entries.filter((name) => {
318
+ if (name.startsWith('_') || name.startsWith('.')) return false;
319
+ return statSync(join(contentDir, name)).isDirectory();
320
+ });
321
+ }
322
+
323
+ /* ------------------------------------------------------------------ 同步 */
324
+
325
+ export const KV_CONTENT_VERSION = 'content_version';
326
+
327
+ export interface SyncOptions {
328
+ /** 直接给定解析后的文件(测试用);缺省扫描 contentDir */
329
+ files?: { section: string; relPath: string; raw: string }[];
330
+ contentDir?: string;
331
+ sections?: string[];
332
+ /**
333
+ * 栏目 frontmatter schema(section 名 → zod schema,M2 Section 协议注入);
334
+ * 缺省全部用基础 frontmatterSchema。
335
+ */
336
+ schemas?: Record<string, ZodType>;
337
+ /** 写 content_version 的 kv(必传,与平台一致的落库 kv) */
338
+ kv: Platform['kv'];
339
+ /** locale 全集(M3,[0] = base):启用后 content/<section>/<locale>/*.md 目录段即 locale */
340
+ locales?: string[];
341
+ /** 测试时钟(缺省 Date.now()) */
342
+ now?: number;
343
+ }
344
+
345
+ export interface SyncReport {
346
+ total: number;
347
+ added: number;
348
+ updated: number;
349
+ removed: number;
350
+ redirectsUpserted: number;
351
+ redirectsRemoved: number;
352
+ contentVersion: string;
353
+ }
354
+
355
+ /**
356
+ * 全量同步(repo 是唯一事实源):
357
+ * - checksum 未变 → 跳过;变了 → 覆盖(含 renderer_version 翻新)
358
+ * - 库里有、repo 没有 → 删除(草稿/正式一视同仁)
359
+ * - redirect_from → redirects 表受控 upsert + 收敛(不在 repo 集合的旧行删除)
360
+ * - content_version = sha256(sorted checksums + count),任何内容变化都会翻新,
361
+ * 写 kv 后经 SWR 缓存键(__v=)使全站渲染缓存整体失效
362
+ */
363
+ export async function syncContent(db: AppDatabase, options: SyncOptions): Promise<SyncReport> {
364
+ const now = options.now ?? Date.now();
365
+ const contentDir = options.contentDir ?? 'content';
366
+ const sections = options.sections ?? scanSectionNames(contentDir);
367
+ const scanned = options.files ?? scanContentDir(contentDir, sections);
368
+
369
+ const files: ContentFile[] = [];
370
+ const issues: string[] = [];
371
+ for (const f of scanned) {
372
+ try {
373
+ files.push(await parseContentFile(f.section, f.relPath, f.raw, now, options.schemas?.[f.section], options.locales));
374
+ } catch (err) {
375
+ if (err instanceof ContentValidationError) issues.push(...err.issues);
376
+ else issues.push(`${f.section}/${f.relPath}: ${(err as Error).message}`);
377
+ }
378
+ }
379
+ if (issues.length) throw new ContentValidationError(issues);
380
+
381
+ const report: SyncReport = { total: files.length, added: 0, updated: 0, removed: 0, redirectsUpserted: 0, redirectsRemoved: 0, contentVersion: '' };
382
+
383
+ // 按 (section, locale) 分组 diff(content 表 UNIQUE 粒度是 section+locale+slug;
384
+ // M3 起同一 section 可同时存在 base 与 variant locale 文件)
385
+ const byGroup = new Map<string, { section: string; locale: string; files: ContentFile[] }>();
386
+ for (const f of files) {
387
+ const key = `${f.section}\u0000${f.locale}`;
388
+ const group = byGroup.get(key) ?? { section: f.section, locale: f.locale, files: [] };
389
+ group.files.push(f);
390
+ byGroup.set(key, group);
391
+ }
392
+
393
+ for (const { section, locale, files: group } of byGroup.values()) {
394
+ const existing = await listSectionChecksums(db, section, locale);
395
+ const existingMap = new Map(existing.map((e) => [e.slug, e.checksum]));
396
+ const upserts: ContentUpsert[] = [];
397
+ const seenSlugs: string[] = [];
398
+
399
+ for (const f of group) {
400
+ seenSlugs.push(f.slug);
401
+ const old = existingMap.get(f.slug);
402
+ if (old === f.checksum) continue; // 内容与渲染版本都没变的行不动
403
+ upserts.push(toUpsert(f, f.bodyHtml));
404
+ if (old === undefined) report.added += 1;
405
+ else report.updated += 1;
406
+ }
407
+
408
+ const removedSlugs = [...existingMap.keys()].filter((s) => !seenSlugs.includes(s));
409
+ if (upserts.length) await upsertContentRows(db, upserts);
410
+ if (removedSlugs.length) {
411
+ await removeContentSlugs(db, section, locale, removedSlugs);
412
+ report.removed += removedSlugs.length;
413
+ }
414
+ }
415
+
416
+ // 重定向:redirect_from 全集 upsert + 收敛(redirects 是 repo 派生表);
417
+ // variant locale 的目标地址带 /<locale> 前缀(与 URL 策略一致)
418
+ const baseLocale = options.locales?.[0] ?? 'zh-CN';
419
+ const redirectRows: RedirectUpsert[] = [];
420
+ const keepFromPaths: string[] = [];
421
+ for (const f of files) {
422
+ const prefix = f.locale !== baseLocale ? `/${f.locale}` : '';
423
+ for (const from of f.redirectFrom) {
424
+ const to = `${prefix}/${f.section}/${f.slug}`;
425
+ if (from === to) continue; // 自指无意义
426
+ redirectRows.push({ fromPath: from, toPath: to, createdAt: new Date(now) });
427
+ keepFromPaths.push(from);
428
+ }
429
+ }
430
+ await upsertRedirects(db, redirectRows);
431
+ report.redirectsUpserted = redirectRows.length;
432
+ report.redirectsRemoved = await removeRedirectsNotIn(db, keepFromPaths);
433
+
434
+ // content_version:全站「路径:checksum」集合的 sha256——增删改、slug 改名、locale
435
+ // 变化任何一种都会翻新,写 kv 后经 SWR 缓存键(__v=)使全站渲染缓存整体失效。
436
+ // 路径段含 locale(与对外 URL 一致:base 无前缀,variant 带 /<locale>)。
437
+ const fingerprints = files
438
+ .map((f) => {
439
+ const base = options.locales?.[0];
440
+ const prefix = base && f.locale !== base ? `${f.locale}/` : '';
441
+ return `${f.section}/${prefix}${f.slug}:${f.checksum}`;
442
+ })
443
+ .sort();
444
+ report.contentVersion = (await sha256Hex(`${fingerprints.join(',')}|${fingerprints.length}`)).slice(0, 32);
445
+ await options.kv.put(KV_CONTENT_VERSION, report.contentVersion);
446
+
447
+ return report;
448
+ }
package/src/db.ts ADDED
@@ -0,0 +1,107 @@
1
+ import type { DrizzleD1Database } from 'drizzle-orm/d1';
2
+ import * as schema from '../drizzle/schema';
3
+ import { kv as kvTable } from '../drizzle/schema';
4
+ import { eq, lt } from 'drizzle-orm';
5
+
6
+ /**
7
+ * service 层统一数据库形态(总设计 §2:方言异构,service 层统一 API)。
8
+ *
9
+ * D1(drizzle-orm/d1)与 better-sqlite3(drizzle-orm/better-sqlite3)的 drizzle
10
+ * 实例共用同一份 sqlite-core 表定义;better-sqlite3 的查询构建器虽同步执行,
11
+ * 但同样是 awaitable 的 QueryPromise,因此在「全部 await」的使用纪律下两者查询面
12
+ * 同形。这里统一按 async 形态(D1 型)声明,node 平台在 platform.node.ts 做
13
+ * 一次类型收窄(附注释),让 service 层单实现覆盖双平台。
14
+ */
15
+ export type AppDatabase = DrizzleD1Database<typeof schema>;
16
+
17
+ export { schema };
18
+
19
+ /* ------------------------------------------------------------------ kv 表实现 */
20
+
21
+ /**
22
+ * 落库版 kv(总设计 §2:workers = D1 `kv` 表,node = sqlite `kv` 表):
23
+ * 接口与 Platform['kv'] 完全一致。
24
+ *
25
+ * M0 的内存 kv 在「sync 脚本写 content_version / dev server 读」跨进程场景下
26
+ * 不成立,M1 起双平台 kv 都落库;表未迁移(尚未跑 sync / d1 migrations)时
27
+ * get/put 静默降级(返回 null / 丢弃写入),绝不让 kv 故障拖垮渲染。
28
+ */
29
+ export function createDbKv(db: AppDatabase): { get(key: string): Promise<string | null>; put(key: string, value: string, ttl?: number): Promise<void>; delete(key: string): Promise<void> } {
30
+ return {
31
+ async get(key: string): Promise<string | null> {
32
+ try {
33
+ const rows = await db.select().from(kvTable).where(eq(kvTable.key, key)).limit(1);
34
+ const row = rows[0];
35
+ if (!row) return null;
36
+ if (row.expiresAt !== null && row.expiresAt.getTime() <= Date.now()) {
37
+ await db.delete(kvTable).where(eq(kvTable.key, key));
38
+ return null;
39
+ }
40
+ return row.value;
41
+ } catch {
42
+ // 表不存在 / 迁移未跑:按未命中处理
43
+ return null;
44
+ }
45
+ },
46
+
47
+ async put(key: string, value: string, ttl?: number): Promise<void> {
48
+ try {
49
+ const expiresAt = ttl ? new Date(Date.now() + ttl * 1000) : null;
50
+ // 受控 upsert(kv 表允许,见 guard-sql 白名单)
51
+ await db
52
+ .insert(kvTable)
53
+ .values({ key, value, expiresAt })
54
+ .onConflictDoUpdate({ target: kvTable.key, set: { value, expiresAt } });
55
+ } catch {
56
+ // 表不存在时静默丢弃(content_version 会退回站点配置常量)
57
+ }
58
+ },
59
+
60
+ async delete(key: string): Promise<void> {
61
+ try {
62
+ await db.delete(kvTable).where(eq(kvTable.key, key));
63
+ } catch {
64
+ // 同上:降级
65
+ }
66
+ },
67
+ };
68
+ }
69
+
70
+ /** 清扫过期 kv 行(后台任务可调用;M1 无定时器,仅供测试/手动维护) */
71
+ export function purgeExpiredKv(db: AppDatabase): Promise<void> {
72
+ return db.delete(kvTable).where(lt(kvTable.expiresAt, new Date())).then(() => undefined);
73
+ }
74
+
75
+ /* ------------------------------------------------------------------ 原子组执行 */
76
+
77
+ interface BatchLikeDb {
78
+ batch(statements: unknown[]): Promise<unknown>;
79
+ }
80
+
81
+ type StatementFactory = (d: AppDatabase) => unknown;
82
+
83
+ /**
84
+ * 原子组写路径(总设计 §10:D1 用 batch 组成原子组,node 用 transaction):
85
+ *
86
+ * - D1(异步驱动):语句建在 db 上 → db.batch([...])(D1 原子批)
87
+ * - better-sqlite3(drizzle 0.45 同步驱动无 batch):语句建在事务句柄上,
88
+ * 回调内逐条 .run(),同处一个 SQLite 事务 —— 与 batch 等价的原子组
89
+ *
90
+ * 调用方传「语句工厂」而非语句本身,因为语句必须建在将执行它的会话上。
91
+ */
92
+ export async function runAtomic(db: AppDatabase, factories: StatementFactory[]): Promise<void> {
93
+ if (!factories.length) return;
94
+ if (typeof (db as unknown as Partial<BatchLikeDb>).batch === 'function') {
95
+ await (db as unknown as BatchLikeDb).batch(factories.map((f) => f(db)));
96
+ return;
97
+ }
98
+ // 同步驱动:事务内逐条执行(顺序敏感的写入组保持原子性)。
99
+ // 类型面统一是 D1 异构 transaction;同步回调体全程无 await,
100
+ // 语句 .run() 均在事务提交前同步完成,这里对形参做一次收窄并绑定 this。
101
+ const syncTransaction = db.transaction as unknown as (cb: (tx: AppDatabase) => void) => unknown;
102
+ await syncTransaction.call(db, (tx) => {
103
+ for (const factory of factories) {
104
+ (factory(tx as unknown as AppDatabase) as { run(): unknown }).run();
105
+ }
106
+ });
107
+ }