@raystack/chronicle 0.1.0-canary.30bf0df → 0.1.0-canary.49fe67c

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 (73) hide show
  1. package/dist/cli/index.js +220 -9919
  2. package/package.json +20 -12
  3. package/src/cli/commands/build.ts +27 -25
  4. package/src/cli/commands/dev.ts +24 -25
  5. package/src/cli/commands/init.ts +38 -132
  6. package/src/cli/commands/serve.ts +36 -49
  7. package/src/cli/commands/start.ts +20 -25
  8. package/src/cli/index.ts +14 -14
  9. package/src/cli/utils/config.ts +25 -26
  10. package/src/cli/utils/index.ts +3 -3
  11. package/src/cli/utils/resolve.ts +9 -3
  12. package/src/cli/utils/scaffold.ts +11 -124
  13. package/src/components/mdx/image.tsx +5 -34
  14. package/src/components/mdx/link.tsx +18 -15
  15. package/src/components/ui/search.module.css +7 -0
  16. package/src/components/ui/search.tsx +65 -49
  17. package/src/lib/config.ts +31 -28
  18. package/src/lib/head.tsx +49 -0
  19. package/src/lib/openapi.ts +8 -8
  20. package/src/lib/page-context.tsx +114 -0
  21. package/src/lib/source.ts +164 -45
  22. package/src/pages/ApiLayout.tsx +33 -0
  23. package/src/pages/ApiPage.tsx +73 -0
  24. package/src/pages/DocsLayout.tsx +18 -0
  25. package/src/pages/DocsPage.tsx +43 -0
  26. package/src/pages/NotFound.tsx +17 -0
  27. package/src/server/App.tsx +67 -0
  28. package/src/server/api/apis-proxy.ts +69 -0
  29. package/src/server/api/health.ts +5 -0
  30. package/src/server/api/page/[...slug].ts +18 -0
  31. package/src/server/api/search.ts +170 -0
  32. package/src/server/api/specs.ts +9 -0
  33. package/src/server/build-search-index.ts +117 -0
  34. package/src/server/entry-client.tsx +70 -0
  35. package/src/server/entry-server.tsx +95 -0
  36. package/src/server/routes/llms.txt.ts +61 -0
  37. package/src/server/routes/og.tsx +75 -0
  38. package/src/server/routes/robots.txt.ts +11 -0
  39. package/src/server/routes/sitemap.xml.ts +39 -0
  40. package/src/server/utils/safe-path.ts +17 -0
  41. package/src/server/vite-config.ts +84 -0
  42. package/src/themes/default/Layout.tsx +69 -42
  43. package/src/themes/default/Page.tsx +9 -11
  44. package/src/themes/default/Toc.tsx +30 -28
  45. package/src/themes/default/index.ts +7 -9
  46. package/src/themes/paper/ChapterNav.tsx +60 -41
  47. package/src/themes/paper/Layout.module.css +1 -1
  48. package/src/themes/paper/Layout.tsx +24 -12
  49. package/src/themes/paper/Page.module.css +11 -4
  50. package/src/themes/paper/Page.tsx +67 -48
  51. package/src/themes/paper/ReadingProgress.tsx +160 -139
  52. package/src/themes/paper/index.ts +5 -5
  53. package/src/themes/registry.ts +7 -7
  54. package/src/types/config.ts +11 -0
  55. package/src/types/content.ts +1 -0
  56. package/src/types/globals.d.ts +4 -0
  57. package/tsconfig.json +2 -3
  58. package/next.config.mjs +0 -10
  59. package/source.config.ts +0 -50
  60. package/src/app/[[...slug]]/layout.tsx +0 -15
  61. package/src/app/[[...slug]]/page.tsx +0 -57
  62. package/src/app/api/apis-proxy/route.ts +0 -59
  63. package/src/app/api/health/route.ts +0 -3
  64. package/src/app/api/search/route.ts +0 -90
  65. package/src/app/apis/[[...slug]]/layout.tsx +0 -26
  66. package/src/app/apis/[[...slug]]/page.tsx +0 -57
  67. package/src/app/layout.tsx +0 -26
  68. package/src/app/llms-full.txt/route.ts +0 -18
  69. package/src/app/llms.txt/route.ts +0 -15
  70. package/src/app/providers.tsx +0 -8
  71. package/src/cli/utils/process.ts +0 -7
  72. package/src/themes/default/font.ts +0 -6
  73. /package/src/{app/apis/[[...slug]]/layout.module.css → pages/ApiLayout.module.css} +0 -0
@@ -0,0 +1,18 @@
1
+ import path from 'node:path';
2
+ import { defineHandler, HTTPError } from 'nitro';
3
+ import { getPage } from '@/lib/source';
4
+
5
+ export default defineHandler(async event => {
6
+ const slugParam = event.context.params?.slug ?? '';
7
+ const slug = slugParam ? slugParam.split('/') : [];
8
+ const page = await getPage(slug);
9
+
10
+ if (!page) {
11
+ throw new HTTPError({ status: 404, message: 'Page not found' });
12
+ }
13
+
14
+ const contentDir = __CHRONICLE_CONTENT_DIR__;
15
+ const relativePath = path.relative(contentDir, page.filePath);
16
+
17
+ return { frontmatter: page.frontmatter, relativePath };
18
+ });
@@ -0,0 +1,170 @@
1
+ import fs from 'node:fs/promises';
2
+ import matter from 'gray-matter';
3
+ import MiniSearch from 'minisearch';
4
+ import { defineHandler } from 'nitro';
5
+ import type { OpenAPIV3 } from 'openapi-types';
6
+ import path from 'node:path';
7
+ import { getSpecSlug } from '@/lib/api-routes';
8
+ import { loadConfig } from '@/lib/config';
9
+ import { loadApiSpecs } from '@/lib/openapi';
10
+
11
+ interface SearchDocument {
12
+ id: string;
13
+ url: string;
14
+ title: string;
15
+ content: string;
16
+ type: 'page' | 'api';
17
+ }
18
+
19
+ let searchIndex: MiniSearch<SearchDocument> | null = null;
20
+ let cachedDocs: SearchDocument[] | null = null;
21
+
22
+ function createIndex(docs: SearchDocument[]): MiniSearch<SearchDocument> {
23
+ const index = new MiniSearch<SearchDocument>({
24
+ fields: ['title', 'content'],
25
+ storeFields: ['url', 'title', 'type'],
26
+ searchOptions: {
27
+ boost: { title: 2 },
28
+ fuzzy: 0.2,
29
+ prefix: true
30
+ }
31
+ });
32
+ index.addAll(docs);
33
+ return index;
34
+ }
35
+
36
+ async function loadPrebuiltIndex(): Promise<SearchDocument[] | null> {
37
+ try {
38
+ const indexPath = path.resolve(__dirname, 'search-index.json');
39
+ const raw = await fs.readFile(indexPath, 'utf-8');
40
+ return JSON.parse(raw);
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ function getContentDir(): string {
47
+ return __CHRONICLE_CONTENT_DIR__ || path.join(process.cwd(), 'content');
48
+ }
49
+
50
+ async function scanContent(): Promise<SearchDocument[]> {
51
+ const contentDir = getContentDir();
52
+ const docs: SearchDocument[] = [];
53
+
54
+ async function scan(dir: string, prefix: string[] = []) {
55
+ try {
56
+ const entries = await fs.readdir(dir, { withFileTypes: true });
57
+ for (const entry of entries) {
58
+ if (entry.name.startsWith('.') || entry.name === 'node_modules')
59
+ continue;
60
+ const fullPath = path.join(dir, entry.name);
61
+
62
+ if (entry.isDirectory()) {
63
+ await scan(fullPath, [...prefix, entry.name]);
64
+ continue;
65
+ }
66
+
67
+ if (!entry.name.endsWith('.mdx') && !entry.name.endsWith('.md'))
68
+ continue;
69
+
70
+ const raw = await fs.readFile(fullPath, 'utf-8');
71
+ const { data: fm, content } = matter(raw);
72
+ const baseName = entry.name.replace(/\.(mdx|md)$/, '');
73
+ const slugs = baseName === 'index' ? prefix : [...prefix, baseName];
74
+ const url = slugs.length === 0 ? '/' : `/${slugs.join('/')}`;
75
+
76
+ docs.push({
77
+ id: url,
78
+ url,
79
+ title: fm.title ?? baseName,
80
+ content: content.slice(0, 5000),
81
+ type: 'page'
82
+ });
83
+ }
84
+ } catch {
85
+ /* directory not readable */
86
+ }
87
+ }
88
+
89
+ await scan(contentDir);
90
+ return docs;
91
+ }
92
+
93
+ async function buildApiDocs(): Promise<SearchDocument[]> {
94
+ const config = loadConfig();
95
+ if (!config.api?.length) return [];
96
+
97
+ const docs: SearchDocument[] = [];
98
+ const specs = await loadApiSpecs(config.api);
99
+
100
+ for (const spec of specs) {
101
+ const specSlug = getSpecSlug(spec);
102
+ const paths = spec.document.paths ?? {};
103
+ for (const [, pathItem] of Object.entries(paths)) {
104
+ if (!pathItem) continue;
105
+ for (const method of ['get', 'post', 'put', 'delete', 'patch'] as const) {
106
+ const op = pathItem[method] as OpenAPIV3.OperationObject | undefined;
107
+ if (!op?.operationId) continue;
108
+ const url = `/apis/${specSlug}/${encodeURIComponent(op.operationId)}`;
109
+ docs.push({
110
+ id: url,
111
+ url,
112
+ title: `${method.toUpperCase()} ${op.summary ?? op.operationId}`,
113
+ content: op.description ?? '',
114
+ type: 'api'
115
+ });
116
+ }
117
+ }
118
+ }
119
+
120
+ return docs;
121
+ }
122
+
123
+ async function loadDocuments(): Promise<SearchDocument[]> {
124
+ const prebuilt = await loadPrebuiltIndex();
125
+ if (prebuilt) return prebuilt;
126
+
127
+ const [contentDocs, apiDocs] = await Promise.all([
128
+ scanContent(),
129
+ buildApiDocs()
130
+ ]);
131
+ return [...contentDocs, ...apiDocs];
132
+ }
133
+
134
+ async function getDocs(): Promise<SearchDocument[]> {
135
+ if (cachedDocs) return cachedDocs;
136
+ cachedDocs = await loadDocuments();
137
+ return cachedDocs;
138
+ }
139
+
140
+ async function getIndex(): Promise<MiniSearch<SearchDocument>> {
141
+ if (searchIndex) return searchIndex;
142
+ const docs = await getDocs();
143
+ searchIndex = createIndex(docs);
144
+ return searchIndex;
145
+ }
146
+
147
+ export default defineHandler(async event => {
148
+ const query = event.url.searchParams.get('query') ?? '';
149
+ const index = await getIndex();
150
+
151
+ if (!query) {
152
+ const docs = await getDocs();
153
+ return docs
154
+ .filter(d => d.type === 'page')
155
+ .slice(0, 8)
156
+ .map(d => ({
157
+ id: d.id,
158
+ url: d.url,
159
+ type: d.type,
160
+ content: d.title
161
+ }));
162
+ }
163
+
164
+ return index.search(query).map(r => ({
165
+ id: r.id,
166
+ url: r.url,
167
+ type: r.type,
168
+ content: r.title
169
+ }));
170
+ });
@@ -0,0 +1,9 @@
1
+ import { defineHandler } from 'nitro';
2
+ import { loadConfig } from '@/lib/config';
3
+ import { loadApiSpecs } from '@/lib/openapi';
4
+
5
+ export default defineHandler(async () => {
6
+ const config = loadConfig();
7
+ const specs = config.api?.length ? await loadApiSpecs(config.api) : [];
8
+ return specs;
9
+ });
@@ -0,0 +1,117 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import matter from 'gray-matter';
4
+ import type { OpenAPIV3 } from 'openapi-types';
5
+ import remarkParse from 'remark-parse';
6
+ import { unified } from 'unified';
7
+ import { visit } from 'unist-util-visit';
8
+ import type { Heading, Text } from 'mdast';
9
+ import { getSpecSlug } from '@/lib/api-routes';
10
+ import { loadConfig } from '@/lib/config';
11
+ import { loadApiSpecs } from '@/lib/openapi';
12
+
13
+ interface SearchDocument {
14
+ id: string;
15
+ url: string;
16
+ title: string;
17
+ content: string;
18
+ type: 'page' | 'api';
19
+ }
20
+
21
+ function extractHeadings(markdown: string): string {
22
+ const tree = unified().use(remarkParse).parse(markdown);
23
+ const headings: string[] = [];
24
+ visit(tree, 'heading', (node: Heading) => {
25
+ const text = node.children
26
+ .filter((child): child is Text => child.type === 'text')
27
+ .map(child => child.value)
28
+ .join('');
29
+ if (text) headings.push(text);
30
+ });
31
+ return headings.join(' ');
32
+ }
33
+
34
+ async function scanContent(contentDir: string): Promise<SearchDocument[]> {
35
+ const docs: SearchDocument[] = [];
36
+
37
+ async function scan(dir: string, prefix: string[] = []) {
38
+ try {
39
+ const entries = await fs.readdir(dir, { withFileTypes: true });
40
+ for (const entry of entries) {
41
+ if (entry.name.startsWith('.') || entry.name === 'node_modules')
42
+ continue;
43
+ const fullPath = path.join(dir, entry.name);
44
+
45
+ if (entry.isDirectory()) {
46
+ await scan(fullPath, [...prefix, entry.name]);
47
+ continue;
48
+ }
49
+
50
+ if (!entry.name.endsWith('.mdx') && !entry.name.endsWith('.md'))
51
+ continue;
52
+
53
+ const raw = await fs.readFile(fullPath, 'utf-8');
54
+ const { data: fm, content } = matter(raw);
55
+ const baseName = entry.name.replace(/\.(mdx|md)$/, '');
56
+ const slugs = baseName === 'index' ? prefix : [...prefix, baseName];
57
+ const url = slugs.length === 0 ? '/' : `/${slugs.join('/')}`;
58
+
59
+ docs.push({
60
+ id: url,
61
+ url,
62
+ title: fm.title ?? baseName,
63
+ content: extractHeadings(content),
64
+ type: 'page'
65
+ });
66
+ }
67
+ } catch {
68
+ /* directory not readable */
69
+ }
70
+ }
71
+
72
+ await scan(contentDir);
73
+ return docs;
74
+ }
75
+
76
+ async function buildApiDocs(): Promise<SearchDocument[]> {
77
+ const config = loadConfig();
78
+ if (!config.api?.length) return [];
79
+
80
+ const docs: SearchDocument[] = [];
81
+ const specs = await loadApiSpecs(config.api);
82
+
83
+ for (const spec of specs) {
84
+ const specSlug = getSpecSlug(spec);
85
+ const paths = spec.document.paths ?? {};
86
+ for (const [, pathItem] of Object.entries(paths)) {
87
+ if (!pathItem) continue;
88
+ for (const method of ['get', 'post', 'put', 'delete', 'patch'] as const) {
89
+ const op = pathItem[method] as OpenAPIV3.OperationObject | undefined;
90
+ if (!op?.operationId) continue;
91
+ const url = `/apis/${specSlug}/${encodeURIComponent(op.operationId)}`;
92
+ docs.push({
93
+ id: url,
94
+ url,
95
+ title: `${method.toUpperCase()} ${op.summary ?? op.operationId}`,
96
+ content: op.description ?? '',
97
+ type: 'api'
98
+ });
99
+ }
100
+ }
101
+ }
102
+
103
+ return docs;
104
+ }
105
+
106
+ export async function generateSearchIndex(contentDir: string, outDir: string) {
107
+ const [contentDocs, apiDocs] = await Promise.all([
108
+ scanContent(contentDir),
109
+ buildApiDocs()
110
+ ]);
111
+
112
+ const documents = [...contentDocs, ...apiDocs];
113
+ const outPath = path.join(outDir, 'search-index.json');
114
+ await fs.writeFile(outPath, JSON.stringify(documents));
115
+
116
+ return documents.length;
117
+ }
@@ -0,0 +1,70 @@
1
+ import '@vitejs/plugin-react/preamble';
2
+ import React from 'react';
3
+ import { hydrateRoot } from 'react-dom/client';
4
+ import { BrowserRouter } from 'react-router';
5
+ import { mdxComponents } from '@/components/mdx';
6
+ import { PageProvider } from '@/lib/page-context';
7
+ import type { ChronicleConfig, Frontmatter, PageTree } from '@/types';
8
+ import type { ApiSpec } from '@/lib/openapi';
9
+ import type { ReactNode } from 'react';
10
+ import { App } from './App';
11
+
12
+ interface EmbeddedData {
13
+ config: ChronicleConfig;
14
+ tree: PageTree;
15
+ slug: string[];
16
+ frontmatter: Frontmatter;
17
+ relativePath: string;
18
+ }
19
+
20
+ async function hydrate() {
21
+ try {
22
+ const embedded = (
23
+ window as unknown as { __PAGE_DATA__?: EmbeddedData }
24
+ ).__PAGE_DATA__;
25
+
26
+ const config: ChronicleConfig = embedded?.config ?? {
27
+ title: 'Documentation'
28
+ };
29
+ const tree: PageTree = embedded?.tree ?? { name: 'root', children: [] };
30
+ const isApiPage =
31
+ window.location.pathname.startsWith('/apis') && !!config.api?.length;
32
+ const apiSpecs: ApiSpec[] = isApiPage
33
+ ? await fetch('/api/specs')
34
+ .then(r => r.json())
35
+ .catch(() => [])
36
+ : [];
37
+
38
+ const page = embedded?.relativePath
39
+ ? await loadPage(embedded)
40
+ : null;
41
+
42
+ hydrateRoot(
43
+ document.getElementById('root') as HTMLElement,
44
+ <BrowserRouter>
45
+ <PageProvider
46
+ initialConfig={config}
47
+ initialTree={tree}
48
+ initialPage={page}
49
+ initialApiSpecs={apiSpecs}
50
+ >
51
+ <App />
52
+ </PageProvider>
53
+ </BrowserRouter>
54
+ );
55
+ } catch (err) {
56
+ console.error('Hydration failed:', err);
57
+ }
58
+ }
59
+
60
+ async function loadPage(
61
+ embedded: EmbeddedData
62
+ ): Promise<{ slug: string[]; frontmatter: Frontmatter; content: ReactNode }> {
63
+ const mod = await import(/* @vite-ignore */ `/.content/${embedded.relativePath}`);
64
+ const content = mod.default
65
+ ? React.createElement(mod.default, { components: mdxComponents })
66
+ : null;
67
+ return { slug: embedded.slug, frontmatter: embedded.frontmatter, content };
68
+ }
69
+
70
+ hydrate();
@@ -0,0 +1,95 @@
1
+ import '@raystack/apsara/normalize.css';
2
+ import '@raystack/apsara/style.css';
3
+ import path from 'node:path';
4
+ import React from 'react';
5
+ import { renderToReadableStream } from 'react-dom/server.edge';
6
+ import { StaticRouter } from 'react-router';
7
+ import { mdxComponents } from '@/components/mdx';
8
+ import { loadConfig } from '@/lib/config';
9
+ import { loadApiSpecs } from '@/lib/openapi';
10
+ import { PageProvider } from '@/lib/page-context';
11
+ import { buildPageTree, getPage, loadPageComponent } from '@/lib/source';
12
+ import { App } from './App';
13
+
14
+ // @ts-expect-error virtual import from Nitro
15
+ import clientAssets from './entry-client?assets=client';
16
+ // @ts-expect-error virtual import from Nitro
17
+ import serverAssets from './entry-server?assets=ssr';
18
+
19
+ export default {
20
+ async fetch(req: Request) {
21
+ const url = new URL(req.url);
22
+ const pathname = url.pathname;
23
+ const slug = pathname === '/' ? [] : pathname.slice(1).split('/').filter(Boolean);
24
+
25
+ const config = loadConfig();
26
+ const apiSpecs = config.api?.length
27
+ ? await loadApiSpecs(config.api).catch(() => [])
28
+ : [];
29
+
30
+ const [tree, sourcePage] = await Promise.all([
31
+ buildPageTree(),
32
+ getPage(slug),
33
+ ]);
34
+
35
+ const pageData = sourcePage
36
+ ? {
37
+ slug,
38
+ frontmatter: sourcePage.frontmatter,
39
+ content: await loadPageComponent(sourcePage).then(component =>
40
+ component ? React.createElement(component, { components: mdxComponents }) : null
41
+ ),
42
+ }
43
+ : null;
44
+
45
+ const relativePath = sourcePage
46
+ ? path.relative(__CHRONICLE_CONTENT_DIR__, sourcePage.filePath)
47
+ : null;
48
+
49
+ const embeddedData = {
50
+ config,
51
+ tree,
52
+ slug,
53
+ frontmatter: pageData?.frontmatter ?? null,
54
+ relativePath,
55
+ };
56
+ const safeJson = JSON.stringify(embeddedData).replace(/</g, '\\u003c');
57
+
58
+ const assets = clientAssets.merge(serverAssets);
59
+
60
+ const stream = await renderToReadableStream(
61
+ <html lang="en">
62
+ <head>
63
+ <meta charSet="UTF-8" />
64
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
65
+ {assets.css.map((attr: { href: string }) => (
66
+ <link key={attr.href} rel="stylesheet" {...attr} />
67
+ ))}
68
+ {assets.js.map((attr: { href: string }) => (
69
+ <link key={attr.href} rel="modulepreload" {...attr} />
70
+ ))}
71
+ <script type="module" src={assets.entry} />
72
+ <script dangerouslySetInnerHTML={{ __html: `window.__PAGE_DATA__ = ${safeJson}` }} />
73
+ </head>
74
+ <body>
75
+ <div id="root">
76
+ <StaticRouter location={pathname}>
77
+ <PageProvider
78
+ initialConfig={config}
79
+ initialTree={tree}
80
+ initialPage={pageData}
81
+ initialApiSpecs={apiSpecs}
82
+ >
83
+ <App />
84
+ </PageProvider>
85
+ </StaticRouter>
86
+ </div>
87
+ </body>
88
+ </html>,
89
+ );
90
+
91
+ return new Response(stream, {
92
+ headers: { 'Content-Type': 'text/html;charset=utf-8' },
93
+ });
94
+ },
95
+ };
@@ -0,0 +1,61 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import matter from 'gray-matter';
4
+ import { defineHandler, HTTPError } from 'nitro';
5
+ import { loadConfig } from '@/lib/config';
6
+
7
+ function getContentDir(): string {
8
+ return __CHRONICLE_CONTENT_DIR__ || path.join(process.cwd(), 'content');
9
+ }
10
+
11
+ async function scanPages(): Promise<{ title: string; url: string }[]> {
12
+ const contentDir = getContentDir();
13
+ const pages: { title: string; url: string }[] = [];
14
+
15
+ async function scan(dir: string, prefix: string[] = []) {
16
+ try {
17
+ const entries = await fs.readdir(dir, { withFileTypes: true });
18
+ for (const entry of entries) {
19
+ if (entry.name.startsWith('.') || entry.name === 'node_modules')
20
+ continue;
21
+ const fullPath = path.join(dir, entry.name);
22
+
23
+ if (entry.isDirectory()) {
24
+ await scan(fullPath, [...prefix, entry.name]);
25
+ continue;
26
+ }
27
+
28
+ if (!entry.name.endsWith('.mdx') && !entry.name.endsWith('.md'))
29
+ continue;
30
+
31
+ const raw = await fs.readFile(fullPath, 'utf-8');
32
+ const { data: fm } = matter(raw);
33
+ const baseName = entry.name.replace(/\.(mdx|md)$/, '');
34
+ const slugs = baseName === 'index' ? prefix : [...prefix, baseName];
35
+ const url = slugs.length === 0 ? '/' : `/${slugs.join('/')}`;
36
+
37
+ pages.push({ title: fm.title ?? baseName, url });
38
+ }
39
+ } catch {
40
+ /* directory not readable */
41
+ }
42
+ }
43
+
44
+ await scan(contentDir);
45
+ return pages;
46
+ }
47
+
48
+ export default defineHandler(async event => {
49
+ const config = loadConfig();
50
+
51
+ if (!config.llms?.enabled) {
52
+ throw new HTTPError({ status: 404, message: 'Not Found' });
53
+ }
54
+
55
+ const pages = await scanPages();
56
+ const index = pages.map(p => `- [${p.title}](${p.url})`).join('\n');
57
+ const body = `# ${config.title}\n\n${config.description ?? ''}\n\n${index}`;
58
+
59
+ event.res.headers.set('Content-Type', 'text/plain');
60
+ return body;
61
+ });
@@ -0,0 +1,75 @@
1
+ import { defineHandler } from 'nitro';
2
+ import React from 'react';
3
+ import satori from 'satori';
4
+ import { loadConfig } from '@/lib/config';
5
+
6
+ let fontData: ArrayBuffer | null = null;
7
+
8
+ async function loadFont(): Promise<ArrayBuffer> {
9
+ if (fontData) return fontData;
10
+
11
+ try {
12
+ const response = await fetch(
13
+ 'https://fonts.gstatic.com/s/inter/v18/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuLyfAZ9hiA.woff2'
14
+ );
15
+ fontData = await response.arrayBuffer();
16
+ } catch {
17
+ fontData = new ArrayBuffer(0);
18
+ }
19
+
20
+ return fontData;
21
+ }
22
+
23
+ export default defineHandler(async event => {
24
+ const config = loadConfig();
25
+ const title = event.url.searchParams.get('title') ?? config.title;
26
+ const description = event.url.searchParams.get('description') ?? '';
27
+ const siteName = config.title;
28
+
29
+ const font = await loadFont();
30
+
31
+ const svg = await satori(
32
+ <div
33
+ style={{
34
+ height: '100%',
35
+ width: '100%',
36
+ display: 'flex',
37
+ flexDirection: 'column',
38
+ justifyContent: 'center',
39
+ padding: '60px 80px',
40
+ backgroundColor: '#0a0a0a',
41
+ color: '#fafafa',
42
+ }}
43
+ >
44
+ <div style={{ fontSize: 24, color: '#888', marginBottom: 16 }}>
45
+ {siteName}
46
+ </div>
47
+ <div
48
+ style={{
49
+ fontSize: 56,
50
+ fontWeight: 700,
51
+ lineHeight: 1.2,
52
+ marginBottom: 24,
53
+ }}
54
+ >
55
+ {title}
56
+ </div>
57
+ {description && (
58
+ <div style={{ fontSize: 24, color: '#999', lineHeight: 1.4 }}>
59
+ {description}
60
+ </div>
61
+ )}
62
+ </div>,
63
+ {
64
+ width: 1200,
65
+ height: 630,
66
+ fonts: [
67
+ { name: 'Inter', data: font, weight: 400, style: 'normal' as const },
68
+ ],
69
+ },
70
+ );
71
+
72
+ event.res.headers.set('Content-Type', 'image/svg+xml');
73
+ event.res.headers.set('Cache-Control', 'public, max-age=86400');
74
+ return svg;
75
+ });
@@ -0,0 +1,11 @@
1
+ import { defineHandler } from 'nitro';
2
+ import { loadConfig } from '@/lib/config';
3
+
4
+ export default defineHandler(event => {
5
+ const config = loadConfig();
6
+ const sitemap = config.url ? `\nSitemap: ${config.url}/sitemap.xml` : '';
7
+ const body = `User-agent: *\nAllow: /${sitemap}`;
8
+
9
+ event.res.headers.set('Content-Type', 'text/plain');
10
+ return body;
11
+ });
@@ -0,0 +1,39 @@
1
+ import { defineHandler } from 'nitro';
2
+ import { buildApiRoutes } from '@/lib/api-routes';
3
+ import { loadConfig } from '@/lib/config';
4
+ import { loadApiSpecs } from '@/lib/openapi';
5
+ import { getPages } from '@/lib/source';
6
+
7
+ export default defineHandler(async event => {
8
+ const config = loadConfig();
9
+
10
+ if (!config.url) {
11
+ event.res.headers.set('Content-Type', 'application/xml');
12
+ return '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>';
13
+ }
14
+
15
+ const baseUrl = config.url.replace(/\/$/, '');
16
+
17
+ const pages = await getPages();
18
+ const docPages = pages.map(page => {
19
+ const lastmod = page.frontmatter.lastModified
20
+ ? `<lastmod>${new Date(page.frontmatter.lastModified).toISOString()}</lastmod>`
21
+ : '';
22
+ return `<url><loc>${baseUrl}/${page.slugs.join('/')}</loc>${lastmod}</url>`;
23
+ });
24
+
25
+ const apiPages = config.api?.length
26
+ ? buildApiRoutes(await loadApiSpecs(config.api)).map(
27
+ route => `<url><loc>${baseUrl}/apis/${route.slug.join('/')}</loc></url>`
28
+ )
29
+ : [];
30
+
31
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
32
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
33
+ <url><loc>${baseUrl}</loc></url>
34
+ ${[...docPages, ...apiPages].join('\n')}
35
+ </urlset>`;
36
+
37
+ event.res.headers.set('Content-Type', 'application/xml');
38
+ return xml;
39
+ });
@@ -0,0 +1,17 @@
1
+ import path from 'node:path';
2
+
3
+ /**
4
+ * Resolve a URL path within a base directory, preventing path traversal.
5
+ * Returns null if the resolved path escapes the base directory.
6
+ */
7
+ export function safePath(baseDir: string, urlPath: string): string | null {
8
+ const decoded = decodeURIComponent(urlPath.split('?')[0]);
9
+ const resolved = path.resolve(baseDir, '.' + decoded);
10
+ if (
11
+ !resolved.startsWith(path.resolve(baseDir) + path.sep) &&
12
+ resolved !== path.resolve(baseDir)
13
+ ) {
14
+ return null;
15
+ }
16
+ return resolved;
17
+ }