@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
@@ -0,0 +1,42 @@
1
+ /** @jsxImportSource hono/jsx */
2
+ import type { Hono } from 'hono';
3
+ import { defineSection } from '../../section';
4
+ import type { EngineContext, Section } from '../../section';
5
+ import { frontmatterSchema } from '../../content';
6
+ import { siteLocales, baseLocaleOf } from '../../i18n';
7
+ import { SearchPage, LandingHomePage } from './views/pages';
8
+ import type { LandingContent } from './views/pages';
9
+
10
+ /**
11
+ * landing 栏目(总设计 §6):站点首页 + 搜索页。
12
+ *
13
+ * / hero / 特性区 / pricing 占位槽 + WebSite(SearchAction) + Organization JSON-LD
14
+ * /search M3 Pagefind 搜索页(/js/search.js island 懒加载 /pagefind/ 索引)
15
+ * /en/** M3 locale 变体(mountLocaleVariants 重挂;SearchAction 落到 /en/search?q=)
16
+ *
17
+ * landing 不是内容型栏目(不消费 content/landing/ 的文档),schema 绑定基础
18
+ * frontmatterSchema:万一有人往 content/landing/ 放文件,同步管线仍按基础
19
+ * 字段校验并入库(运行时读取路径由将来需要时再接)。
20
+ */
21
+ export function createLandingSection(content: LandingContent = {}): Section {
22
+ return defineSection({
23
+ name: 'landing',
24
+ schema: frontmatterSchema,
25
+ seo: {
26
+ listPage: { path: '/', title: 'Home', changefreq: 'daily', priority: 1.0 },
27
+ inFeeds: false,
28
+ },
29
+ routes(app: Hono, ctx: EngineContext): void {
30
+ const config = ctx.config;
31
+ const locales = siteLocales(config);
32
+ const locale = ctx.locale ?? baseLocaleOf(locales);
33
+
34
+ app.get('/', (c) => c.html(<LandingHomePage c={c} config={config} content={content} locale={locale} />));
35
+
36
+ app.get('/search', (c) => {
37
+ const query = (c.req.query('q') ?? '').slice(0, 100);
38
+ return c.html(<SearchPage c={c} config={config} query={query} locale={locale} />);
39
+ });
40
+ },
41
+ });
42
+ }
@@ -0,0 +1,218 @@
1
+ /** @jsxImportSource hono/jsx */
2
+ import { buildHead, organizationJsonLd, websiteWithSearchJsonLd } from '../../../seo';
3
+ import { tr, localePath, hreflangAlternates, siteLocales, baseLocaleOf, localeSwitchProps } from '../../../i18n';
4
+ import type { EngineConfig } from '../../../types';
5
+ import { Layout } from '../../../views/layout';
6
+ import type { Context } from 'hono';
7
+
8
+ /**
9
+ * landing 视图:站点首页(hero / 特性区 / pricing 占位槽,tokens 驱动)
10
+ * 与 /search 搜索页(M3 Pagefind island)。
11
+ */
12
+
13
+ export interface LandingFeature {
14
+ title: string;
15
+ desc: string;
16
+ }
17
+
18
+ export interface LandingPricingTier {
19
+ name: string;
20
+ value: string;
21
+ note: string;
22
+ }
23
+
24
+ export interface LandingContent {
25
+ kicker?: string;
26
+ title?: string;
27
+ sub?: string;
28
+ primaryAction?: { label: string; href: string };
29
+ secondaryAction?: { label: string; href: string };
30
+ features?: LandingFeature[];
31
+ pricingTitle?: string;
32
+ pricingNote?: string;
33
+ pricingTiers?: LandingPricingTier[];
34
+ }
35
+
36
+ const DEFAULTS: Required<Omit<LandingContent, 'features' | 'pricingTiers'>> & { features: LandingFeature[]; pricingTiers: LandingPricingTier[] } = {
37
+ kicker: 'kit 建站引擎',
38
+ title: '静态内核,动态能力',
39
+ sub: 'Hono 双入口(Workers / Node)、SWR 渲染缓存、Section 插件协议、零客户端框架。渲染在服务端完成,交互按需挂载。',
40
+ primaryAction: { label: '快速上手', href: '/docs' },
41
+ secondaryAction: { label: '阅读博客', href: '/blog' },
42
+ features: [
43
+ { title: 'Section 协议', desc: '栏目即插件:路由、frontmatter schema、SEO 声明一体注册,一行配置启用一个栏目。' },
44
+ { title: 'SWR 缓存', desc: 'fresh / stale / miss 三路径;缓存键内嵌内容版本与渲染器版本,发布即整体翻新。' },
45
+ { title: '账户体系', desc: 'better-auth 接线:WebCrypto PBKDF2 口令散列,drizzle 四表 session,读写路径分离缓存。' },
46
+ ],
47
+ pricingTitle: 'Pricing',
48
+ pricingNote: '占位槽位:接计费/SaaS 时替换为真实方案(见父任务 Out of Scope)。',
49
+ pricingTiers: [
50
+ { name: 'Starter', value: '¥0', note: '自部署:Workers 免费额度内起步。' },
51
+ { name: 'Pro', value: '¥--', note: '占位:自定义域名 + 内容同步管线。' },
52
+ { name: 'Team', value: '¥--', note: '占位:多栏目协作与审计。' },
53
+ ],
54
+ };
55
+
56
+ /** en 变体文案(显式传递:locale 视图注入,英文版首页不用中文默认值) */
57
+ const DEFAULTS_EN: Required<Omit<LandingContent, 'features' | 'pricingTiers'>> & { features: LandingFeature[]; pricingTiers: LandingPricingTier[] } = {
58
+ ...DEFAULTS,
59
+ kicker: 'kit site engine',
60
+ title: 'Static core, dynamic capability',
61
+ sub: 'Hono dual entry (Workers / Node), SWR render cache, Section plugin protocol, zero client framework. Rendering happens on the server; interactivity mounts on demand.',
62
+ primaryAction: { label: 'Get started', href: '/docs' },
63
+ secondaryAction: { label: 'Read the blog', href: '/blog' },
64
+ features: [
65
+ { title: 'Section protocol', desc: 'Sections are plugins: routes, frontmatter schema and SEO declarations register as one, one config line per section.' },
66
+ { title: 'SWR cache', desc: 'fresh / stale / miss paths; cache keys embed content and renderer versions, so a release refreshes everything.' },
67
+ { title: 'Accounts', desc: 'better-auth wiring: WebCrypto PBKDF2 password hashing, drizzle four-table sessions, cache separation for reads and writes.' },
68
+ ],
69
+ pricingNote: 'Placeholder slot: swap in a real billing/SaaS story when needed.',
70
+ pricingTiers: [
71
+ { name: 'Starter', value: '$0', note: 'Self-hosted: start within the Workers free tier.' },
72
+ { name: 'Pro', value: '$--', note: 'Placeholder: custom domain + content sync pipeline.' },
73
+ { name: 'Team', value: '$--', note: 'Placeholder: multi-section collaboration and audit.' },
74
+ ],
75
+ };
76
+
77
+ function originOf(config: EngineConfig): string {
78
+ return config.site.url.replace(/\/+$/, '');
79
+ }
80
+
81
+ /* ------------------------------------------------------------ 首页 */
82
+
83
+ export function LandingHomePage(props: { c: Context; config: EngineConfig; content: LandingContent; locale?: string }) {
84
+ const { site } = props.config;
85
+ const locales = siteLocales(props.config);
86
+ const locale = props.locale ?? baseLocaleOf(locales);
87
+ const prefix = locale !== baseLocaleOf(locales) ? `/${locale}` : '';
88
+ const t = tr(locale);
89
+ const base = originOf(props.config);
90
+ const c0 =
91
+ locale === baseLocaleOf(locales)
92
+ ? { ...DEFAULTS, ...props.content }
93
+ : { ...DEFAULTS_EN, ...props.content };
94
+ const searchTemplate = `${base}${localePath('/search', locale, locales)}?q={query}`;
95
+ const head = buildHead({
96
+ title: `${site.name}${site.tagline ? ` - ${site.tagline}` : ''}`,
97
+ description: site.description,
98
+ canonical: `${base}${prefix === '' ? '/' : prefix}`,
99
+ type: 'website',
100
+ locale,
101
+ hreflang: locales.length > 1 ? hreflangAlternates(base, '/', locales) : [],
102
+ });
103
+ const jsonld = [
104
+ organizationJsonLd(site),
105
+ websiteWithSearchJsonLd(site, searchTemplate),
106
+ ];
107
+
108
+ return (
109
+ <Layout head={head} jsonld={jsonld} brand={site.name} lang={locale} localeSwitch={localeSwitchProps(props.c, props.config, locale)} footerNote={`${site.name} · ${t.footer_note()}`}>
110
+ <section class="hero">
111
+ <div class="container">
112
+ <p class="hero-kicker">{c0.kicker}</p>
113
+ <h1 class="hero-title">{c0.title || site.tagline}</h1>
114
+ <p class="hero-sub">{c0.sub}</p>
115
+ <div class="hero-actions">
116
+ {c0.primaryAction && <a class="button button-primary" href={c0.primaryAction.href}>{c0.primaryAction.label}</a>}
117
+ {c0.secondaryAction && <a class="button" href={c0.secondaryAction.href}>{c0.secondaryAction.label}</a>}
118
+ </div>
119
+ </div>
120
+ </section>
121
+
122
+ <section class="section" aria-label="features">
123
+ <div class="container feature-grid">
124
+ {c0.features.map((f) => (
125
+ <div class="feature-card">
126
+ <h2 class="feature-title">{f.title}</h2>
127
+ <p>{f.desc}</p>
128
+ </div>
129
+ ))}
130
+ </div>
131
+ </section>
132
+
133
+ <section class="section" aria-label="pricing">
134
+ <div class="container">
135
+ <h2 class="feature-title">{c0.pricingTitle}</h2>
136
+ <div class="pricing-grid">
137
+ {c0.pricingTiers.map((tp) => (
138
+ <div class="price-card">
139
+ <h3 class="price-card-name">{tp.name}</h3>
140
+ <p class="price-card-value">{tp.value}</p>
141
+ <p class="price-card-note">{tp.note}</p>
142
+ </div>
143
+ ))}
144
+ </div>
145
+ <p class="search-hint">{c0.pricingNote}</p>
146
+ </div>
147
+ </section>
148
+ </Layout>
149
+ );
150
+ }
151
+
152
+ /* ------------------------------------------------------------ /search(Pagefind island) */
153
+
154
+ /**
155
+ * 搜索页:表单 + 搜索 island 容器。结果由 /js/search.js 懒加载
156
+ * /pagefind/pagefind.js 绘制(构建期 scripts/build-search.ts 产出索引);
157
+ * 文案经 paraglide 服务端注入 data-* 属性({query} 由 island 端替换)。
158
+ */
159
+ export function SearchPage(props: { c: Context; config: EngineConfig; query: string; locale?: string }) {
160
+ const { site } = props.config;
161
+ const locales = siteLocales(props.config);
162
+ const locale = props.locale ?? baseLocaleOf(locales);
163
+ const prefix = locale !== baseLocaleOf(locales) ? `/${locale}` : '';
164
+ const t = tr(locale);
165
+ const base = originOf(props.config);
166
+ const actionPath = `${prefix}/search`;
167
+ const head = buildHead({
168
+ title: `${t.search_title()} - ${site.name}`,
169
+ description: t.search_description(),
170
+ canonical: `${base}${actionPath}`,
171
+ type: 'website',
172
+ locale,
173
+ noindex: true,
174
+ });
175
+
176
+ return (
177
+ <Layout head={head} jsonld={[]} brand={site.name} lang={locale} localeSwitch={localeSwitchProps(props.c, props.config, locale)} footerNote={`${site.name} · ${t.footer_note()}`}>
178
+ <section class="search-page">
179
+ <p class="hero-kicker">{t.search_kicker()}</p>
180
+ <h1 class="hero-title">{t.search_title()}</h1>
181
+ <form class="search-form" action={actionPath} method="get" role="search">
182
+ <label class="search-label" for="search-input">{t.search_input_label()}</label>
183
+ <div class="search-row">
184
+ <input
185
+ id="search-input"
186
+ class="search-input"
187
+ type="search"
188
+ name="q"
189
+ value={props.query}
190
+ placeholder={t.search_input_placeholder()}
191
+ maxlength={100}
192
+ autocomplete="off"
193
+ />
194
+ <button class="button button-primary" type="submit">{t.search_submit()}</button>
195
+ </div>
196
+ </form>
197
+ <div
198
+ class="search-results"
199
+ data-island="search"
200
+ data-q={props.query}
201
+ data-search-root="/pagefind/pagefind.js"
202
+ data-tpl-loading={t.search_loading()}
203
+ data-tpl-empty={t.search_empty_hint()}
204
+ data-tpl-error={t.search_error()}
205
+ data-tpl-results-for={t.search_results_for({ query: '{query}' })}
206
+ data-tpl-no-results={t.search_no_results({ query: '{query}' })}
207
+ data-tpl-count={t.search_results_count({ count: '{count}' })}
208
+ data-tpl-powered={t.search_powered()}
209
+ />
210
+ {/* 搜索 island:懒加载 /pagefind/ 索引(budget 口径:懒加载 chunk 不计入首屏 20KB 红线) */}
211
+ <script type="module" src="/js/search.js"></script>
212
+ <p class="search-hint">
213
+ {t.search_powered()}
214
+ </p>
215
+ </section>
216
+ </Layout>
217
+ );
218
+ }
package/src/seo.ts ADDED
@@ -0,0 +1,193 @@
1
+ import { escapeHtml, safeJsonForScript } from './html';
2
+ import type { SiteMeta } from './types';
3
+
4
+ /* ------------------------------------------------------------------ head */
5
+
6
+ export interface HeadSpec {
7
+ title: string;
8
+ description?: string;
9
+ canonical?: string;
10
+ /** og:type,默认 website */
11
+ type?: string;
12
+ image?: string;
13
+ locale?: string;
14
+ hreflang?: { hreflang: string; href: string }[];
15
+ noindex?: boolean;
16
+ }
17
+
18
+ /**
19
+ * 组装 <head> 内的 SEO 片段(title/meta/og/twitter/hreflang)。
20
+ * 全部插值经 escapeHtml,输出安全 HTML 字符串;缺数据的行不输出。
21
+ */
22
+ export function buildHead(spec: HeadSpec): string {
23
+ const parts: string[] = [];
24
+ const push = (s: string): void => {
25
+ parts.push(s);
26
+ };
27
+
28
+ push(`<title>${escapeHtml(spec.title)}</title>`);
29
+ if (spec.description) push(`<meta name="description" content="${escapeHtml(spec.description)}">`);
30
+ if (spec.noindex) push(`<meta name="robots" content="noindex">`);
31
+ if (spec.canonical) push(`<link rel="canonical" href="${escapeHtml(spec.canonical)}">`);
32
+
33
+ // Open Graph
34
+ push(`<meta property="og:site_name" content="${escapeHtml(spec.title.split(' - ')[0] ?? spec.title)}">`);
35
+ push(`<meta property="og:title" content="${escapeHtml(spec.title)}">`);
36
+ if (spec.description) push(`<meta property="og:description" content="${escapeHtml(spec.description)}">`);
37
+ push(`<meta property="og:type" content="${escapeHtml(spec.type ?? 'website')}">`);
38
+ if (spec.canonical) push(`<meta property="og:url" content="${escapeHtml(spec.canonical)}">`);
39
+ if (spec.image) push(`<meta property="og:image" content="${escapeHtml(spec.image)}">`);
40
+ if (spec.locale) push(`<meta property="og:locale" content="${escapeHtml(spec.locale)}">`);
41
+
42
+ // Twitter
43
+ push(`<meta name="twitter:card" content="${spec.image ? 'summary_large_image' : 'summary'}">`);
44
+ push(`<meta name="twitter:title" content="${escapeHtml(spec.title)}">`);
45
+ if (spec.description) push(`<meta name="twitter:description" content="${escapeHtml(spec.description)}">`);
46
+ if (spec.image) push(`<meta name="twitter:image" content="${escapeHtml(spec.image)}">`);
47
+
48
+ for (const alt of spec.hreflang ?? []) {
49
+ push(`<link rel="alternate" hreflang="${escapeHtml(alt.hreflang)}" href="${escapeHtml(alt.href)}">`);
50
+ }
51
+
52
+ return parts.join('\n');
53
+ }
54
+
55
+ /* ------------------------------------------------------------------ JSON-LD */
56
+
57
+ /**
58
+ * JSON-LD 构造器统一约定:数据齐全才返回对象,否则返回 null(不输出残缺结构)。
59
+ */
60
+
61
+ export function organizationJsonLd(site: SiteMeta): object | null {
62
+ if (!site.name || !site.url) return null;
63
+ return {
64
+ '@context': 'https://schema.org',
65
+ '@type': 'Organization',
66
+ name: site.name,
67
+ url: site.url,
68
+ logo: `${site.url.replace(/\/+$/, '')}/favicon.svg`,
69
+ };
70
+ }
71
+
72
+ export function websiteWithSearchJsonLd(site: SiteMeta, searchUrl?: string): object | null {
73
+ if (!site.name || !site.url || !searchUrl) return null;
74
+ return {
75
+ '@context': 'https://schema.org',
76
+ '@type': 'WebSite',
77
+ name: site.name,
78
+ url: site.url,
79
+ potentialAction: {
80
+ '@type': 'SearchAction',
81
+ target: {
82
+ '@type': 'EntryPoint',
83
+ urlTemplate: searchUrl,
84
+ },
85
+ 'query-input': 'required name=query',
86
+ },
87
+ };
88
+ }
89
+
90
+ /** 输出可直接注入 <head> 的 JSON-LD script 标签(防 </script> 逃逸) */
91
+ export function jsonLdScriptTag(obj: object): string {
92
+ return `<script type="application/ld+json">${safeJsonForScript(obj)}</script>`;
93
+ }
94
+
95
+ export interface PersonInput {
96
+ name?: string | null;
97
+ url?: string | null;
98
+ }
99
+
100
+ /** Person(文章 author);name 缺失即 null */
101
+ export function personJsonLd(input: PersonInput): object | null {
102
+ const name = (input.name ?? '').trim();
103
+ if (!name) return null;
104
+ const obj: Record<string, unknown> = { '@type': 'Person', name };
105
+ if (input.url) obj.url = input.url;
106
+ return { '@context': 'https://schema.org', ...obj };
107
+ }
108
+
109
+ export interface ArticleJsonLdInput {
110
+ url: string;
111
+ headline: string;
112
+ description?: string;
113
+ datePublished?: Date | null;
114
+ dateModified?: Date | null;
115
+ author?: PersonInput;
116
+ image?: string;
117
+ section?: string;
118
+ siteName?: string;
119
+ }
120
+
121
+ /** Article(BlogPosting 语义);url+headline 齐全才输出 */
122
+ export function articleJsonLd(input: ArticleJsonLdInput): object | null {
123
+ if (!input.url || !input.headline) return null;
124
+ const author = personJsonLd(input.author ?? {});
125
+ const obj: Record<string, unknown> = {
126
+ '@context': 'https://schema.org',
127
+ '@type': 'Article',
128
+ headline: input.headline,
129
+ mainEntityOfPage: { '@type': 'WebPage', '@id': input.url },
130
+ };
131
+ if (input.description) obj.description = input.description;
132
+ if (input.datePublished) obj.datePublished = input.datePublished.toISOString();
133
+ if (input.dateModified) obj.dateModified = input.dateModified.toISOString();
134
+ if (author) obj.author = author;
135
+ if (input.image) obj.image = input.image;
136
+ if (input.section) obj.articleSection = input.section;
137
+ if (input.siteName) obj.publisher = { '@type': 'Organization', name: input.siteName };
138
+ return obj;
139
+ }
140
+
141
+ export interface CollectionPageJsonLdInput {
142
+ url: string;
143
+ name: string;
144
+ description?: string;
145
+ /** 列表条目(可选,name+url 齐全的条目才进 item 列表) */
146
+ items?: { name: string; url: string }[];
147
+ }
148
+
149
+ /** CollectionPage;url+name 齐全才输出 */
150
+ export function collectionPageJsonLd(input: CollectionPageJsonLdInput): object | null {
151
+ if (!input.url || !input.name) return null;
152
+ const obj: Record<string, unknown> = {
153
+ '@context': 'https://schema.org',
154
+ '@type': 'CollectionPage',
155
+ name: input.name,
156
+ url: input.url,
157
+ };
158
+ if (input.description) obj.description = input.description;
159
+ const items = (input.items ?? []).filter((i) => i.name && i.url);
160
+ if (items.length) {
161
+ obj.mainEntity = {
162
+ '@type': 'ItemList',
163
+ itemListElement: items.map((i, idx) => ({
164
+ '@type': 'ListItem',
165
+ position: idx + 1,
166
+ name: i.name,
167
+ url: i.url,
168
+ })),
169
+ };
170
+ }
171
+ return obj;
172
+ }
173
+
174
+ export interface BreadcrumbInput {
175
+ name?: string | null;
176
+ url?: string | null;
177
+ }
178
+
179
+ /** BreadcrumbList;≥2 级且全部 name+url 齐全才输出(单级是噪音) */
180
+ export function breadcrumbJsonLd(items: BreadcrumbInput[]): object | null {
181
+ const clean = items.filter((i) => (i.name ?? '').trim() && i.url);
182
+ if (clean.length < 2 || clean.length !== items.length) return null;
183
+ return {
184
+ '@context': 'https://schema.org',
185
+ '@type': 'BreadcrumbList',
186
+ itemListElement: clean.map((i, idx) => ({
187
+ '@type': 'ListItem',
188
+ position: idx + 1,
189
+ name: i.name,
190
+ item: i.url,
191
+ })),
192
+ };
193
+ }
package/src/server.ts ADDED
@@ -0,0 +1,122 @@
1
+ import { Hono } from 'hono';
2
+ import { securityHeaders, errorEnvelope, notFoundHandler } from './guard';
3
+ import { rateLimitMiddleware } from './ratelimit';
4
+ import { swrMiddleware, createContentVersionResolver } from './cache';
5
+ import { registerFeeds } from './feeds';
6
+ import { registerSections, homeClaimedBy, mountLocaleVariants } from './section';
7
+ import { createAuthStack, mountAuth } from './auth';
8
+ import { registerMediaRoute } from './media';
9
+ import { TURNSTILE_SCRIPT_ORIGIN } from './turnstile';
10
+ import { escapeHtml } from './html';
11
+ import { siteLocales, i18nEnabled, localePath, stripLocalePrefix, LOCALE_COOKIE } from './i18n';
12
+ import type { EngineConfig } from './types';
13
+
14
+ /* ------------------------------------------------------------ 引擎内置兜底页 */
15
+
16
+ /** 站点层未注入视图时的极简占位首页(仍带 tokens/base 链接,保持 warm 主题一致) */
17
+ function builtinHome(c: Parameters<NonNullable<EngineConfig['renderHome']>>[0], site: EngineConfig['site']): Response {
18
+ const html =
19
+ '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
20
+ `<title>${escapeHtml(site.name)}</title>` +
21
+ '<link rel="stylesheet" href="/css/tokens.css"><link rel="stylesheet" href="/css/base.css"></head>' +
22
+ '<body><main class="home-fallback">' +
23
+ `<h1>${escapeHtml(site.name)}</h1><p>${escapeHtml(site.tagline ?? 'kit 建站引擎已就绪')}</p>` +
24
+ '</main></body></html>';
25
+ return c.body(html, 200, { 'content-type': 'text/html; charset=utf-8' });
26
+ }
27
+
28
+ /* ------------------------------------------------------------ createApp */
29
+
30
+ /**
31
+ * 组装唯一 Hono app(总设计 §3 渲染管线,M2 起 section 驱动):
32
+ *
33
+ * 请求 → securityHeaders → ratelimit → cacheSWR(GET HTML) → auth/sections/media → feeds → 404
34
+ * onError → /api/* JSON envelope / 页面 errorPage
35
+ *
36
+ * 内容路由全部经 registerSections 挂载(引擎无内置内容路由);
37
+ * 账户体系由 createAuthStack 建、mountAuth 挂(/api/auth/* + 账户页)。
38
+ * 双入口(entry-workers / entry-node)都从这里拿 app,site.config.ts 注入配置。
39
+ */
40
+ export function createApp(config: EngineConfig): Hono {
41
+ const app = new Hono();
42
+
43
+ // content_version 解析器:swr 缓存键与 feeds Etag 共享(kv 驱动 + 30s memo)
44
+ const resolveContentVersion = createContentVersionResolver(config.platform, config.contentVersion);
45
+
46
+ // Turnstile 启用与否决定 CSP 是否追加其源(静态 CSP 常量保持自源红线)
47
+ const auth = createAuthStack(config);
48
+ const securityOptions = auth.turnstile.enabled
49
+ ? { cspScriptSrcExtra: [TURNSTILE_SCRIPT_ORIGIN], cspFrameSrcExtra: [TURNSTILE_SCRIPT_ORIGIN] }
50
+ : undefined;
51
+
52
+ // 中间件链(注册顺序即执行顺序;安全头对缓存命中的响应同样生效)
53
+ app.use('*', securityHeaders(securityOptions));
54
+ app.use('*', rateLimitMiddleware(config.platform));
55
+ app.use('*', swrMiddleware(app, config, resolveContentVersion));
56
+
57
+ // 健康检查:不进 SWR,no-store
58
+ app.get('/healthz', (c) =>
59
+ c.json({ ok: true, ts: Date.now() }, 200, {
60
+ 'cache-control': 'no-store',
61
+ }),
62
+ );
63
+
64
+ // favicon 兜底:301 到 SVG,301 一律 no-store(避免中间缓存钉死旧地址)
65
+ app.get('/favicon.ico', (c) => c.redirect('/favicon.svg', 301));
66
+
67
+ // M2 sections:blog/docs/landing 等栏目路由(含 landing 的 / 与 /search)
68
+ const sections = config.sections ?? [];
69
+ const locales = siteLocales(config);
70
+ const registered = registerSections(app, { platform: config.platform, config }, sections);
71
+
72
+ // M3 locale 变体:locales > 1 时为每个 variant locale 挂 '/<locale>/**' 前缀路由
73
+ // (重用同一 section 渲染,ctx.locale 注入渲染语言);单语言零开销不挂载
74
+ mountLocaleVariants(app, { platform: config.platform, config }, sections, locales);
75
+
76
+ // M3 语言切换端点:/lang/:code?next=/blog → 301 到 /<code>/blog + 写 kit_lang cookie
77
+ // (301 一律 no-store;cookie 供后续协商链消费。next 只接受站内绝对路径防开放重定向)
78
+ if (i18nEnabled(locales)) {
79
+ app.get('/lang/:code', (c) => {
80
+ const code = c.req.param('code');
81
+ if (!code || !locales.includes(code)) return notFoundHandler(config)(c);
82
+ const rawNext = c.req.query('next') ?? '/';
83
+ const next =
84
+ rawNext.startsWith('/') && !rawNext.startsWith('//') && !rawNext.includes('://') && !rawNext.includes('../')
85
+ ? stripLocalePrefix(rawNext, locales)
86
+ : '/';
87
+ const target = localePath(next, code, locales);
88
+ return new Response(null, {
89
+ status: 301,
90
+ headers: {
91
+ location: target,
92
+ 'cache-control': 'no-store',
93
+ 'set-cookie': `${LOCALE_COOKIE}=${code}; Path=/; Max-Age=31536000; SameSite=Lax${c.req.url.startsWith('https://') ? '; Secure' : ''}`,
94
+ },
95
+ });
96
+ });
97
+ }
98
+
99
+ // 兜底首页:无 section 认领 '/' 时挂站点注入的 renderHome;未注入则退回
100
+ // 引擎内置极简占位首页(否则 blog/docs-only 站点的首页 404,首跑体验断裂)
101
+ if (!homeClaimedBy(sections)) {
102
+ app.get('/', (c) => (config.renderHome ? config.renderHome(c) : builtinHome(c, config.site)));
103
+ }
104
+
105
+ // M2 auth:/api/auth/* + /login /register /settings 账户页
106
+ mountAuth(app, config, auth);
107
+
108
+ // M2 media:/media/:key storage 代理(immutable 长缓存)
109
+ registerMediaRoute(app, config);
110
+
111
+ // SEO feeds:sitemap / robots / rss / atom / llms.txt(Etag = content_version;
112
+ // sitemap/llms 的栏目页条目来自 section seo 声明,无 sections 时退回内置默认)
113
+ registerFeeds(app, config, resolveContentVersion, registered.seo);
114
+
115
+ // 404(/api/* 走 JSON envelope;页面走 errorPage;一律 no-store)
116
+ app.notFound(notFoundHandler(config));
117
+
118
+ // 错误 envelope
119
+ app.onError(errorEnvelope(config));
120
+
121
+ return app;
122
+ }