@raystack/chronicle 0.1.0-canary.111b55a
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.
- package/bin/chronicle.js +2 -0
- package/dist/cli/index.js +963 -0
- package/package.json +67 -0
- package/src/cli/__tests__/config.test.ts +25 -0
- package/src/cli/__tests__/scaffold.test.ts +10 -0
- package/src/cli/commands/build.ts +74 -0
- package/src/cli/commands/dev.ts +21 -0
- package/src/cli/commands/init.ts +154 -0
- package/src/cli/commands/serve.ts +55 -0
- package/src/cli/commands/start.ts +24 -0
- package/src/cli/index.ts +21 -0
- package/src/cli/utils/config.ts +43 -0
- package/src/cli/utils/index.ts +2 -0
- package/src/cli/utils/resolve.ts +6 -0
- package/src/cli/utils/scaffold.ts +20 -0
- package/src/components/api/code-snippets.module.css +7 -0
- package/src/components/api/code-snippets.tsx +76 -0
- package/src/components/api/endpoint-page.module.css +58 -0
- package/src/components/api/endpoint-page.tsx +283 -0
- package/src/components/api/field-row.module.css +126 -0
- package/src/components/api/field-row.tsx +204 -0
- package/src/components/api/field-section.module.css +24 -0
- package/src/components/api/field-section.tsx +100 -0
- package/src/components/api/index.ts +8 -0
- package/src/components/api/json-editor.module.css +9 -0
- package/src/components/api/json-editor.tsx +61 -0
- package/src/components/api/key-value-editor.module.css +13 -0
- package/src/components/api/key-value-editor.tsx +62 -0
- package/src/components/api/method-badge.module.css +4 -0
- package/src/components/api/method-badge.tsx +29 -0
- package/src/components/api/response-panel.module.css +8 -0
- package/src/components/api/response-panel.tsx +44 -0
- package/src/components/common/breadcrumb.tsx +3 -0
- package/src/components/common/button.tsx +3 -0
- package/src/components/common/callout.module.css +7 -0
- package/src/components/common/callout.tsx +27 -0
- package/src/components/common/code-block.tsx +3 -0
- package/src/components/common/dialog.tsx +3 -0
- package/src/components/common/index.ts +10 -0
- package/src/components/common/input-field.tsx +3 -0
- package/src/components/common/sidebar.tsx +3 -0
- package/src/components/common/switch.tsx +3 -0
- package/src/components/common/table.tsx +3 -0
- package/src/components/common/tabs.tsx +3 -0
- package/src/components/mdx/code.module.css +42 -0
- package/src/components/mdx/code.tsx +36 -0
- package/src/components/mdx/details.module.css +14 -0
- package/src/components/mdx/details.tsx +17 -0
- package/src/components/mdx/image.tsx +24 -0
- package/src/components/mdx/index.tsx +35 -0
- package/src/components/mdx/link.tsx +37 -0
- package/src/components/mdx/mermaid.module.css +9 -0
- package/src/components/mdx/mermaid.tsx +37 -0
- package/src/components/mdx/paragraph.module.css +8 -0
- package/src/components/mdx/paragraph.tsx +19 -0
- package/src/components/mdx/table.tsx +40 -0
- package/src/components/ui/breadcrumbs.tsx +72 -0
- package/src/components/ui/client-theme-switcher.tsx +18 -0
- package/src/components/ui/footer.module.css +27 -0
- package/src/components/ui/footer.tsx +31 -0
- package/src/components/ui/search.module.css +111 -0
- package/src/components/ui/search.tsx +173 -0
- package/src/lib/api-routes.ts +120 -0
- package/src/lib/config.ts +56 -0
- package/src/lib/head.tsx +45 -0
- package/src/lib/index.ts +2 -0
- package/src/lib/openapi.ts +188 -0
- package/src/lib/page-context.tsx +95 -0
- package/src/lib/remark-unused-directives.ts +30 -0
- package/src/lib/schema.ts +99 -0
- package/src/lib/snippet-generators.ts +87 -0
- package/src/lib/source.ts +138 -0
- package/src/pages/ApiLayout.module.css +22 -0
- package/src/pages/ApiLayout.tsx +29 -0
- package/src/pages/ApiPage.tsx +68 -0
- package/src/pages/DocsLayout.tsx +18 -0
- package/src/pages/DocsPage.tsx +43 -0
- package/src/pages/NotFound.tsx +10 -0
- package/src/pages/__tests__/head.test.tsx +57 -0
- package/src/server/App.tsx +59 -0
- package/src/server/__tests__/entry-server.test.tsx +35 -0
- package/src/server/__tests__/handlers.test.ts +77 -0
- package/src/server/__tests__/og.test.ts +23 -0
- package/src/server/__tests__/router.test.ts +72 -0
- package/src/server/__tests__/vite-config.test.ts +25 -0
- package/src/server/adapters/vercel.ts +133 -0
- package/src/server/build-search-index.ts +107 -0
- package/src/server/dev.ts +156 -0
- package/src/server/entry-client.tsx +74 -0
- package/src/server/entry-prod.ts +97 -0
- package/src/server/entry-server.tsx +35 -0
- package/src/server/entry-vercel.ts +28 -0
- package/src/server/handlers/apis-proxy.ts +52 -0
- package/src/server/handlers/health.ts +3 -0
- package/src/server/handlers/llms.ts +58 -0
- package/src/server/handlers/og.ts +87 -0
- package/src/server/handlers/robots.ts +11 -0
- package/src/server/handlers/search.ts +172 -0
- package/src/server/handlers/sitemap.ts +39 -0
- package/src/server/handlers/specs.ts +9 -0
- package/src/server/index.html +12 -0
- package/src/server/prod.ts +18 -0
- package/src/server/request-handler.ts +63 -0
- package/src/server/router.ts +42 -0
- package/src/server/vite-config.ts +71 -0
- package/src/themes/default/Layout.module.css +81 -0
- package/src/themes/default/Layout.tsx +132 -0
- package/src/themes/default/Page.module.css +106 -0
- package/src/themes/default/Page.tsx +21 -0
- package/src/themes/default/Toc.module.css +48 -0
- package/src/themes/default/Toc.tsx +66 -0
- package/src/themes/default/font.ts +4 -0
- package/src/themes/default/index.ts +13 -0
- package/src/themes/paper/ChapterNav.module.css +71 -0
- package/src/themes/paper/ChapterNav.tsx +95 -0
- package/src/themes/paper/Layout.module.css +33 -0
- package/src/themes/paper/Layout.tsx +25 -0
- package/src/themes/paper/Page.module.css +174 -0
- package/src/themes/paper/Page.tsx +106 -0
- package/src/themes/paper/ReadingProgress.module.css +132 -0
- package/src/themes/paper/ReadingProgress.tsx +294 -0
- package/src/themes/paper/index.ts +8 -0
- package/src/themes/registry.ts +14 -0
- package/src/types/config.ts +80 -0
- package/src/types/content.ts +36 -0
- package/src/types/index.ts +3 -0
- package/src/types/theme.ts +22 -0
- package/tsconfig.json +29 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import path from 'path'
|
|
2
|
+
import fs from 'fs/promises'
|
|
3
|
+
import { existsSync } from 'fs'
|
|
4
|
+
import chalk from 'chalk'
|
|
5
|
+
|
|
6
|
+
interface VercelAdapterOptions {
|
|
7
|
+
distDir: string
|
|
8
|
+
contentDir: string
|
|
9
|
+
projectRoot: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const CONTENT_EXTENSIONS = new Set([
|
|
13
|
+
'.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.ico',
|
|
14
|
+
'.pdf', '.json', '.yaml', '.yml', '.txt',
|
|
15
|
+
])
|
|
16
|
+
|
|
17
|
+
export async function buildVercelOutput(options: VercelAdapterOptions) {
|
|
18
|
+
const { distDir, contentDir, projectRoot } = options
|
|
19
|
+
const outputDir = path.resolve(projectRoot, '.vercel/output')
|
|
20
|
+
|
|
21
|
+
console.log(chalk.gray('Generating Vercel output...'))
|
|
22
|
+
|
|
23
|
+
// Clean previous output
|
|
24
|
+
await fs.rm(outputDir, { recursive: true, force: true })
|
|
25
|
+
|
|
26
|
+
// Create output directories
|
|
27
|
+
const staticDir = path.resolve(outputDir, 'static')
|
|
28
|
+
const funcDir = path.resolve(outputDir, 'functions/index.func')
|
|
29
|
+
await fs.mkdir(staticDir, { recursive: true })
|
|
30
|
+
await fs.mkdir(funcDir, { recursive: true })
|
|
31
|
+
|
|
32
|
+
// 1. Copy client assets → .vercel/output/static/
|
|
33
|
+
const clientDir = path.resolve(distDir, 'client')
|
|
34
|
+
await copyDir(clientDir, staticDir)
|
|
35
|
+
console.log(chalk.gray(' Copied client assets to static/'))
|
|
36
|
+
|
|
37
|
+
// 2. Copy content dir assets (images, etc.) → .vercel/output/static/
|
|
38
|
+
if (existsSync(contentDir)) {
|
|
39
|
+
await copyContentAssets(contentDir, staticDir)
|
|
40
|
+
console.log(chalk.gray(' Copied content assets to static/'))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// 3. Copy server bundle → .vercel/output/functions/index.func/
|
|
44
|
+
const serverDir = path.resolve(distDir, 'server')
|
|
45
|
+
await copyDir(serverDir, funcDir)
|
|
46
|
+
console.log(chalk.gray(' Copied server bundle to functions/'))
|
|
47
|
+
|
|
48
|
+
// 4. Copy HTML template into function dir (not accessible from static/ at runtime)
|
|
49
|
+
const templateSrc = path.resolve(clientDir, 'src/server/index.html')
|
|
50
|
+
await fs.copyFile(templateSrc, path.resolve(funcDir, 'index.html'))
|
|
51
|
+
|
|
52
|
+
// 5. Write package.json for ESM support
|
|
53
|
+
await fs.writeFile(
|
|
54
|
+
path.resolve(funcDir, 'package.json'),
|
|
55
|
+
JSON.stringify({ type: 'module' }, null, 2),
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
// 6. Write .vc-config.json
|
|
59
|
+
await fs.writeFile(
|
|
60
|
+
path.resolve(funcDir, '.vc-config.json'),
|
|
61
|
+
JSON.stringify({
|
|
62
|
+
runtime: 'nodejs24.x',
|
|
63
|
+
handler: 'entry-vercel.js',
|
|
64
|
+
launcherType: 'Nodejs',
|
|
65
|
+
}, null, 2),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
// 7. Write config.json
|
|
69
|
+
await fs.writeFile(
|
|
70
|
+
path.resolve(outputDir, 'config.json'),
|
|
71
|
+
JSON.stringify({
|
|
72
|
+
version: 3,
|
|
73
|
+
routes: [
|
|
74
|
+
{ handle: 'filesystem' },
|
|
75
|
+
{ src: '/(.*)', dest: '/index' },
|
|
76
|
+
],
|
|
77
|
+
}, null, 2),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
console.log(chalk.green('Vercel output generated →'), outputDir)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function copyDir(src: string, dest: string) {
|
|
84
|
+
await fs.mkdir(dest, { recursive: true })
|
|
85
|
+
const entries = await fs.readdir(src, { withFileTypes: true })
|
|
86
|
+
|
|
87
|
+
for (const entry of entries) {
|
|
88
|
+
const srcPath = path.join(src, entry.name)
|
|
89
|
+
const destPath = path.join(dest, entry.name)
|
|
90
|
+
|
|
91
|
+
if (entry.isDirectory()) {
|
|
92
|
+
await copyDir(srcPath, destPath)
|
|
93
|
+
} else {
|
|
94
|
+
await fs.copyFile(srcPath, destPath)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function copyContentAssets(contentDir: string, staticDir: string) {
|
|
100
|
+
const entries = await fs.readdir(contentDir, { withFileTypes: true })
|
|
101
|
+
|
|
102
|
+
for (const entry of entries) {
|
|
103
|
+
const srcPath = path.join(contentDir, entry.name)
|
|
104
|
+
|
|
105
|
+
if (entry.isDirectory()) {
|
|
106
|
+
const destSubDir = path.join(staticDir, entry.name)
|
|
107
|
+
await copyContentAssetsRecursive(srcPath, destSubDir)
|
|
108
|
+
} else {
|
|
109
|
+
const ext = path.extname(entry.name).toLowerCase()
|
|
110
|
+
if (CONTENT_EXTENSIONS.has(ext)) {
|
|
111
|
+
await fs.copyFile(srcPath, path.join(staticDir, entry.name))
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function copyContentAssetsRecursive(srcDir: string, destDir: string) {
|
|
118
|
+
const entries = await fs.readdir(srcDir, { withFileTypes: true })
|
|
119
|
+
|
|
120
|
+
for (const entry of entries) {
|
|
121
|
+
const srcPath = path.join(srcDir, entry.name)
|
|
122
|
+
|
|
123
|
+
if (entry.isDirectory()) {
|
|
124
|
+
await copyContentAssetsRecursive(srcPath, path.join(destDir, entry.name))
|
|
125
|
+
} else {
|
|
126
|
+
const ext = path.extname(entry.name).toLowerCase()
|
|
127
|
+
if (CONTENT_EXTENSIONS.has(ext)) {
|
|
128
|
+
await fs.mkdir(destDir, { recursive: true })
|
|
129
|
+
await fs.copyFile(srcPath, path.join(destDir, entry.name))
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import fs from 'fs/promises'
|
|
2
|
+
import path from 'path'
|
|
3
|
+
import matter from 'gray-matter'
|
|
4
|
+
import { loadConfig } from '@/lib/config'
|
|
5
|
+
import { loadApiSpecs } from '@/lib/openapi'
|
|
6
|
+
import { getSpecSlug } from '@/lib/api-routes'
|
|
7
|
+
import type { OpenAPIV3 } from 'openapi-types'
|
|
8
|
+
|
|
9
|
+
interface SearchDocument {
|
|
10
|
+
id: string
|
|
11
|
+
url: string
|
|
12
|
+
title: string
|
|
13
|
+
content: string
|
|
14
|
+
type: 'page' | 'api'
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function extractHeadings(markdown: string): string {
|
|
18
|
+
const headingRegex = /^#{1,6}\s+(.+)$/gm
|
|
19
|
+
const headings: string[] = []
|
|
20
|
+
let match
|
|
21
|
+
while ((match = headingRegex.exec(markdown)) !== null) {
|
|
22
|
+
headings.push(match[1].trim())
|
|
23
|
+
}
|
|
24
|
+
return headings.join(' ')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function scanContent(contentDir: string): Promise<SearchDocument[]> {
|
|
28
|
+
const docs: SearchDocument[] = []
|
|
29
|
+
|
|
30
|
+
async function scan(dir: string, prefix: string[] = []) {
|
|
31
|
+
let entries
|
|
32
|
+
try { entries = await fs.readdir(dir, { withFileTypes: true }) }
|
|
33
|
+
catch { return }
|
|
34
|
+
|
|
35
|
+
for (const entry of entries) {
|
|
36
|
+
if (entry.name.startsWith('.') || entry.name === 'node_modules') continue
|
|
37
|
+
const fullPath = path.join(dir, entry.name)
|
|
38
|
+
|
|
39
|
+
if (entry.isDirectory()) {
|
|
40
|
+
await scan(fullPath, [...prefix, entry.name])
|
|
41
|
+
continue
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (!entry.name.endsWith('.mdx') && !entry.name.endsWith('.md')) continue
|
|
45
|
+
|
|
46
|
+
const raw = await fs.readFile(fullPath, 'utf-8')
|
|
47
|
+
const { data: fm, content } = matter(raw)
|
|
48
|
+
const baseName = entry.name.replace(/\.(mdx|md)$/, '')
|
|
49
|
+
const slugs = baseName === 'index' ? prefix : [...prefix, baseName]
|
|
50
|
+
const url = slugs.length === 0 ? '/' : '/' + slugs.join('/')
|
|
51
|
+
|
|
52
|
+
docs.push({
|
|
53
|
+
id: url,
|
|
54
|
+
url,
|
|
55
|
+
title: fm.title ?? baseName,
|
|
56
|
+
content: extractHeadings(content),
|
|
57
|
+
type: 'page',
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
await scan(contentDir)
|
|
63
|
+
return docs
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function buildApiDocs(): SearchDocument[] {
|
|
67
|
+
const config = loadConfig()
|
|
68
|
+
if (!config.api?.length) return []
|
|
69
|
+
|
|
70
|
+
const docs: SearchDocument[] = []
|
|
71
|
+
const specs = loadApiSpecs(config.api)
|
|
72
|
+
|
|
73
|
+
for (const spec of specs) {
|
|
74
|
+
const specSlug = getSpecSlug(spec)
|
|
75
|
+
const paths = spec.document.paths ?? {}
|
|
76
|
+
for (const [, pathItem] of Object.entries(paths)) {
|
|
77
|
+
if (!pathItem) continue
|
|
78
|
+
for (const method of ['get', 'post', 'put', 'delete', 'patch'] as const) {
|
|
79
|
+
const op = pathItem[method] as OpenAPIV3.OperationObject | undefined
|
|
80
|
+
if (!op?.operationId) continue
|
|
81
|
+
const url = `/apis/${specSlug}/${encodeURIComponent(op.operationId)}`
|
|
82
|
+
docs.push({
|
|
83
|
+
id: url,
|
|
84
|
+
url,
|
|
85
|
+
title: `${method.toUpperCase()} ${op.summary ?? op.operationId}`,
|
|
86
|
+
content: op.description ?? '',
|
|
87
|
+
type: 'api',
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return docs
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export async function generateSearchIndex(contentDir: string, outDir: string) {
|
|
97
|
+
const [contentDocs, apiDocs] = await Promise.all([
|
|
98
|
+
scanContent(contentDir),
|
|
99
|
+
Promise.resolve(buildApiDocs()),
|
|
100
|
+
])
|
|
101
|
+
|
|
102
|
+
const documents = [...contentDocs, ...apiDocs]
|
|
103
|
+
const outPath = path.join(outDir, 'search-index.json')
|
|
104
|
+
await fs.writeFile(outPath, JSON.stringify(documents))
|
|
105
|
+
|
|
106
|
+
return documents.length
|
|
107
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { createServer as createViteServer } from 'vite'
|
|
2
|
+
import { createServer } from 'http'
|
|
3
|
+
import fsPromises from 'fs/promises'
|
|
4
|
+
import { createReadStream } from 'fs'
|
|
5
|
+
import path from 'path'
|
|
6
|
+
import chalk from 'chalk'
|
|
7
|
+
import { createViteConfig } from './vite-config'
|
|
8
|
+
|
|
9
|
+
export interface DevServerOptions {
|
|
10
|
+
port: number
|
|
11
|
+
root: string
|
|
12
|
+
contentDir: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function startDevServer(options: DevServerOptions) {
|
|
16
|
+
const { port, root, contentDir } = options
|
|
17
|
+
|
|
18
|
+
const viteConfig = await createViteConfig({ root, contentDir, isDev: true })
|
|
19
|
+
const vite = await createViteServer({
|
|
20
|
+
...viteConfig,
|
|
21
|
+
server: { middlewareMode: true },
|
|
22
|
+
appType: 'custom',
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
const templatePath = path.resolve(root, 'src/server/index.html')
|
|
26
|
+
|
|
27
|
+
const server = createServer(async (req, res) => {
|
|
28
|
+
const url = req.url || '/'
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
// Let Vite handle its own requests (HMR, modules)
|
|
32
|
+
if (url.startsWith('/@') || url.startsWith('/__vite') || url.startsWith('/node_modules/')) {
|
|
33
|
+
vite.middlewares(req, res, () => {
|
|
34
|
+
res.statusCode = 404
|
|
35
|
+
res.end()
|
|
36
|
+
})
|
|
37
|
+
return
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Serve static files from content dir (skip .md/.mdx)
|
|
41
|
+
const contentFile = path.join(contentDir, decodeURIComponent(url.split('?')[0]))
|
|
42
|
+
if (!url.endsWith('.md') && !url.endsWith('.mdx')) {
|
|
43
|
+
try {
|
|
44
|
+
const stat = await fsPromises.stat(contentFile)
|
|
45
|
+
if (stat.isFile()) {
|
|
46
|
+
const ext = path.extname(contentFile).toLowerCase()
|
|
47
|
+
const mimeTypes: Record<string, string> = {
|
|
48
|
+
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
49
|
+
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.webp': 'image/webp',
|
|
50
|
+
'.ico': 'image/x-icon', '.pdf': 'application/pdf', '.json': 'application/json',
|
|
51
|
+
'.yaml': 'text/yaml', '.yml': 'text/yaml', '.txt': 'text/plain',
|
|
52
|
+
}
|
|
53
|
+
res.setHeader('Content-Type', mimeTypes[ext] || 'application/octet-stream')
|
|
54
|
+
createReadStream(contentFile).pipe(res)
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
} catch { /* fall through to SSR */ }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Let Vite handle JS/CSS/TS module requests and other static assets
|
|
61
|
+
if (/\.(js|ts|tsx|css|map)(\?|$)/.test(url)) {
|
|
62
|
+
vite.middlewares(req, res, () => {
|
|
63
|
+
res.statusCode = 404
|
|
64
|
+
res.end()
|
|
65
|
+
})
|
|
66
|
+
return
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Check API/static routes (load through Vite SSR for import.meta.glob support)
|
|
70
|
+
const { matchRoute } = await vite.ssrLoadModule(path.resolve(root, 'src/server/router.ts'))
|
|
71
|
+
const routeHandler = matchRoute(new URL(url, `http://localhost:${port}`).href)
|
|
72
|
+
if (routeHandler) {
|
|
73
|
+
const request = new Request(new URL(url, `http://localhost:${port}`))
|
|
74
|
+
const response = await routeHandler(request)
|
|
75
|
+
res.statusCode = response.status
|
|
76
|
+
response.headers.forEach((value: string, key: string) => res.setHeader(key, value))
|
|
77
|
+
const body = await response.text()
|
|
78
|
+
res.end(body)
|
|
79
|
+
return
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Resolve page data before SSR render
|
|
83
|
+
const pathname = new URL(url, `http://localhost:${port}`).pathname
|
|
84
|
+
const slug = pathname === '/' ? [] : pathname.slice(1).split('/').filter(Boolean)
|
|
85
|
+
|
|
86
|
+
const source = await vite.ssrLoadModule(path.resolve(root, 'src/lib/source.ts'))
|
|
87
|
+
const { mdxComponents } = await vite.ssrLoadModule(path.resolve(root, 'src/components/mdx/index.tsx'))
|
|
88
|
+
const { loadConfig } = await vite.ssrLoadModule(path.resolve(root, 'src/lib/config.ts'))
|
|
89
|
+
|
|
90
|
+
const config = loadConfig()
|
|
91
|
+
|
|
92
|
+
const { loadApiSpecs } = await vite.ssrLoadModule(path.resolve(root, 'src/lib/openapi.ts'))
|
|
93
|
+
const apiSpecs = config.api?.length ? loadApiSpecs(config.api) : []
|
|
94
|
+
|
|
95
|
+
const [tree, sourcePage] = await Promise.all([
|
|
96
|
+
source.buildPageTree(),
|
|
97
|
+
source.getPage(slug),
|
|
98
|
+
])
|
|
99
|
+
|
|
100
|
+
let pageData = null
|
|
101
|
+
// Don't embed apiSpecs — too large. Client fetches via /api/specs
|
|
102
|
+
let embeddedData: any = { config, tree, slug, frontmatter: null, filePath: null }
|
|
103
|
+
|
|
104
|
+
if (sourcePage) {
|
|
105
|
+
const component = await source.loadPageComponent(sourcePage)
|
|
106
|
+
const React = await import('react')
|
|
107
|
+
const MDXBody = component
|
|
108
|
+
pageData = {
|
|
109
|
+
slug,
|
|
110
|
+
frontmatter: sourcePage.frontmatter,
|
|
111
|
+
content: MDXBody ? React.createElement(MDXBody, { components: mdxComponents }) : null,
|
|
112
|
+
}
|
|
113
|
+
embeddedData.frontmatter = sourcePage.frontmatter
|
|
114
|
+
embeddedData.filePath = sourcePage.filePath
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// SSR render
|
|
118
|
+
let template = await fsPromises.readFile(templatePath, 'utf-8')
|
|
119
|
+
template = await vite.transformIndexHtml(url, template)
|
|
120
|
+
|
|
121
|
+
// Embed page data for client hydration
|
|
122
|
+
const dataScript = `<script>window.__PAGE_DATA__ = ${JSON.stringify(embeddedData)}</script>`
|
|
123
|
+
template = template.replace('<!--head-outlet-->', `<!--head-outlet-->${dataScript}`)
|
|
124
|
+
|
|
125
|
+
const { render } = await vite.ssrLoadModule(path.resolve(root, 'src/server/entry-server.tsx'))
|
|
126
|
+
|
|
127
|
+
const html = render(url, { config, tree, page: pageData, apiSpecs })
|
|
128
|
+
const finalHtml = template.replace('<!--ssr-outlet-->', html)
|
|
129
|
+
|
|
130
|
+
res.setHeader('Content-Type', 'text/html')
|
|
131
|
+
res.statusCode = 200
|
|
132
|
+
res.end(finalHtml)
|
|
133
|
+
} catch (e) {
|
|
134
|
+
vite.ssrFixStacktrace(e as Error)
|
|
135
|
+
console.error(e)
|
|
136
|
+
res.statusCode = 500
|
|
137
|
+
res.end((e as Error).message)
|
|
138
|
+
}
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
server.listen(port, () => {
|
|
142
|
+
console.log(chalk.cyan(`\n Chronicle dev server running at:`))
|
|
143
|
+
console.log(chalk.green(` http://localhost:${port}\n`))
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
// Graceful shutdown
|
|
147
|
+
const shutdown = () => {
|
|
148
|
+
vite.close()
|
|
149
|
+
server.close()
|
|
150
|
+
process.exit(0)
|
|
151
|
+
}
|
|
152
|
+
process.on('SIGINT', shutdown)
|
|
153
|
+
process.on('SIGTERM', shutdown)
|
|
154
|
+
|
|
155
|
+
return { server, vite }
|
|
156
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { hydrateRoot } from 'react-dom/client'
|
|
2
|
+
import { BrowserRouter } from 'react-router-dom'
|
|
3
|
+
import { PageProvider } from '@/lib/page-context'
|
|
4
|
+
import { App } from './App'
|
|
5
|
+
import { getPage, loadPageComponent, buildPageTree } from '@/lib/source'
|
|
6
|
+
import { mdxComponents } from '@/components/mdx'
|
|
7
|
+
import type { ChronicleConfig, PageTree } from '@/types'
|
|
8
|
+
import type { ApiSpec } from '@/lib/openapi'
|
|
9
|
+
import type { ReactNode } from 'react'
|
|
10
|
+
import React from 'react'
|
|
11
|
+
|
|
12
|
+
interface EmbeddedData {
|
|
13
|
+
config: ChronicleConfig
|
|
14
|
+
tree: PageTree
|
|
15
|
+
slug: string[]
|
|
16
|
+
frontmatter: { title: string; description?: string; order?: number }
|
|
17
|
+
filePath: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function hydrate() {
|
|
21
|
+
try {
|
|
22
|
+
const embedded: EmbeddedData | undefined = (window as any).__PAGE_DATA__
|
|
23
|
+
|
|
24
|
+
let config: ChronicleConfig = { title: 'Documentation' }
|
|
25
|
+
let tree: PageTree = { name: 'root', children: [] }
|
|
26
|
+
let page: { slug: string[]; frontmatter: any; content: ReactNode } | null = null
|
|
27
|
+
let apiSpecs: ApiSpec[] = []
|
|
28
|
+
|
|
29
|
+
if (embedded) {
|
|
30
|
+
config = embedded.config
|
|
31
|
+
tree = embedded.tree
|
|
32
|
+
|
|
33
|
+
// Fetch API specs if on /apis route
|
|
34
|
+
const isApiRoute = window.location.pathname.startsWith('/apis')
|
|
35
|
+
if (isApiRoute && config.api?.length) {
|
|
36
|
+
try {
|
|
37
|
+
const res = await fetch('/api/specs')
|
|
38
|
+
apiSpecs = await res.json()
|
|
39
|
+
} catch { /* will load on demand */ }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const sourcePage = await getPage(embedded.slug)
|
|
43
|
+
if (sourcePage) {
|
|
44
|
+
const component = await loadPageComponent(sourcePage)
|
|
45
|
+
page = {
|
|
46
|
+
slug: embedded.slug,
|
|
47
|
+
frontmatter: embedded.frontmatter,
|
|
48
|
+
content: component ? React.createElement(component, { components: mdxComponents }) : null,
|
|
49
|
+
}
|
|
50
|
+
} else {
|
|
51
|
+
page = {
|
|
52
|
+
slug: embedded.slug,
|
|
53
|
+
frontmatter: embedded.frontmatter,
|
|
54
|
+
content: null,
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
} else {
|
|
58
|
+
tree = await buildPageTree()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
hydrateRoot(
|
|
62
|
+
document.getElementById('root') as HTMLElement,
|
|
63
|
+
<BrowserRouter>
|
|
64
|
+
<PageProvider initialConfig={config} initialTree={tree} initialPage={page} initialApiSpecs={apiSpecs}>
|
|
65
|
+
<App />
|
|
66
|
+
</PageProvider>
|
|
67
|
+
</BrowserRouter>,
|
|
68
|
+
)
|
|
69
|
+
} catch (err) {
|
|
70
|
+
console.error('Hydration failed:', err)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
hydrate()
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Production server entry — built by Vite, loaded by prod.ts at runtime
|
|
2
|
+
import { createServer } from 'http'
|
|
3
|
+
import { readFileSync, createReadStream } from 'fs'
|
|
4
|
+
import fsPromises from 'fs/promises'
|
|
5
|
+
import path from 'path'
|
|
6
|
+
import { render } from './entry-server'
|
|
7
|
+
import { matchRoute } from './router'
|
|
8
|
+
import { loadConfig } from '@/lib/config'
|
|
9
|
+
import { loadApiSpecs } from '@/lib/openapi'
|
|
10
|
+
import { getPage, loadPageComponent, buildPageTree } from '@/lib/source'
|
|
11
|
+
import { handleRequest } from './request-handler'
|
|
12
|
+
|
|
13
|
+
export { render, matchRoute, loadConfig, loadApiSpecs, getPage, loadPageComponent, buildPageTree }
|
|
14
|
+
|
|
15
|
+
async function writeResponse(res: import('http').ServerResponse, response: Response) {
|
|
16
|
+
res.statusCode = response.status
|
|
17
|
+
response.headers.forEach((value: string, key: string) => res.setHeader(key, value))
|
|
18
|
+
const body = await response.text()
|
|
19
|
+
res.end(body)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function startServer(options: { port: number; distDir: string }) {
|
|
23
|
+
const { port, distDir } = options
|
|
24
|
+
|
|
25
|
+
const clientDir = path.resolve(distDir, 'client')
|
|
26
|
+
const templatePath = path.resolve(clientDir, 'src/server/index.html')
|
|
27
|
+
const template = readFileSync(templatePath, 'utf-8')
|
|
28
|
+
|
|
29
|
+
const sirv = (await import('sirv')).default
|
|
30
|
+
const assets = sirv(clientDir, { gzip: true })
|
|
31
|
+
|
|
32
|
+
const baseUrl = `http://localhost:${port}`
|
|
33
|
+
|
|
34
|
+
const server = createServer(async (req, res) => {
|
|
35
|
+
const url = req.url || '/'
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
// API routes — handled by shared request handler
|
|
39
|
+
const routeHandler = matchRoute(new URL(url, baseUrl).href)
|
|
40
|
+
if (routeHandler) {
|
|
41
|
+
const response = await routeHandler(new Request(new URL(url, baseUrl)))
|
|
42
|
+
await writeResponse(res, response)
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Serve static files from content dir (skip .md/.mdx)
|
|
47
|
+
const contentDir = process.env.CHRONICLE_CONTENT_DIR || process.cwd()
|
|
48
|
+
const contentFile = path.join(contentDir, decodeURIComponent(url.split('?')[0]))
|
|
49
|
+
if (!url.endsWith('.md') && !url.endsWith('.mdx')) {
|
|
50
|
+
try {
|
|
51
|
+
const stat = await fsPromises.stat(contentFile)
|
|
52
|
+
if (stat.isFile()) {
|
|
53
|
+
const ext = path.extname(contentFile).toLowerCase()
|
|
54
|
+
const mimeTypes: Record<string, string> = {
|
|
55
|
+
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
56
|
+
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.webp': 'image/webp',
|
|
57
|
+
'.ico': 'image/x-icon', '.pdf': 'application/pdf', '.json': 'application/json',
|
|
58
|
+
'.yaml': 'text/yaml', '.yml': 'text/yaml', '.txt': 'text/plain',
|
|
59
|
+
}
|
|
60
|
+
res.setHeader('Content-Type', mimeTypes[ext] || 'application/octet-stream')
|
|
61
|
+
createReadStream(contentFile).pipe(res)
|
|
62
|
+
return
|
|
63
|
+
}
|
|
64
|
+
} catch { /* fall through */ }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Static assets from dist/client
|
|
68
|
+
const assetHandled = await new Promise<boolean>((resolve) => {
|
|
69
|
+
assets(req, res, () => resolve(false))
|
|
70
|
+
res.on('close', () => resolve(true))
|
|
71
|
+
})
|
|
72
|
+
if (assetHandled) return
|
|
73
|
+
|
|
74
|
+
// SSR render — handled by shared request handler
|
|
75
|
+
const response = await handleRequest(url, { template, baseUrl })
|
|
76
|
+
await writeResponse(res, response)
|
|
77
|
+
} catch (e) {
|
|
78
|
+
console.error(e)
|
|
79
|
+
res.statusCode = 500
|
|
80
|
+
res.end((e as Error).message)
|
|
81
|
+
}
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
server.listen(port, () => {
|
|
85
|
+
console.log(`\n Chronicle production server running at:`)
|
|
86
|
+
console.log(` http://localhost:${port}\n`)
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
const shutdown = () => {
|
|
90
|
+
server.close()
|
|
91
|
+
process.exit(0)
|
|
92
|
+
}
|
|
93
|
+
process.on('SIGINT', shutdown)
|
|
94
|
+
process.on('SIGTERM', shutdown)
|
|
95
|
+
|
|
96
|
+
return server
|
|
97
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { renderToString } from 'react-dom/server'
|
|
2
|
+
import { StaticRouter } from 'react-router-dom'
|
|
3
|
+
import { PageProvider } from '@/lib/page-context'
|
|
4
|
+
import { App } from './App'
|
|
5
|
+
import type { ReactNode } from 'react'
|
|
6
|
+
import type { ChronicleConfig, Frontmatter, PageTree } from '@/types'
|
|
7
|
+
import type { ApiSpec } from '@/lib/openapi'
|
|
8
|
+
|
|
9
|
+
export interface SSRData {
|
|
10
|
+
config: ChronicleConfig
|
|
11
|
+
tree: PageTree
|
|
12
|
+
page: {
|
|
13
|
+
slug: string[]
|
|
14
|
+
frontmatter: Frontmatter
|
|
15
|
+
content: ReactNode
|
|
16
|
+
} | null
|
|
17
|
+
apiSpecs: ApiSpec[]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function render(url: string, data: SSRData): string {
|
|
21
|
+
const pathname = new URL(url, 'http://localhost').pathname
|
|
22
|
+
|
|
23
|
+
return renderToString(
|
|
24
|
+
<StaticRouter location={pathname}>
|
|
25
|
+
<PageProvider
|
|
26
|
+
initialConfig={data.config}
|
|
27
|
+
initialTree={data.tree}
|
|
28
|
+
initialPage={data.page}
|
|
29
|
+
initialApiSpecs={data.apiSpecs}
|
|
30
|
+
>
|
|
31
|
+
<App />
|
|
32
|
+
</PageProvider>
|
|
33
|
+
</StaticRouter>,
|
|
34
|
+
)
|
|
35
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Vercel serverless function entry — built by Vite, deployed as catch-all function
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from 'http'
|
|
3
|
+
import { readFileSync } from 'fs'
|
|
4
|
+
import { fileURLToPath } from 'url'
|
|
5
|
+
import path from 'path'
|
|
6
|
+
import { handleRequest } from './request-handler'
|
|
7
|
+
|
|
8
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
9
|
+
const templatePath = path.resolve(__dirname, 'index.html')
|
|
10
|
+
const template = readFileSync(templatePath, 'utf-8')
|
|
11
|
+
|
|
12
|
+
export default async function handler(req: IncomingMessage, res: ServerResponse) {
|
|
13
|
+
const url = req.url || '/'
|
|
14
|
+
const baseUrl = `https://${req.headers.host || 'localhost'}`
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
const response = await handleRequest(url, { template, baseUrl })
|
|
18
|
+
|
|
19
|
+
res.statusCode = response.status
|
|
20
|
+
response.headers.forEach((value: string, key: string) => res.setHeader(key, value))
|
|
21
|
+
const body = await response.text()
|
|
22
|
+
res.end(body)
|
|
23
|
+
} catch (e) {
|
|
24
|
+
console.error(e)
|
|
25
|
+
res.statusCode = 500
|
|
26
|
+
res.end((e as Error).message)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { loadConfig } from '@/lib/config'
|
|
2
|
+
import { loadApiSpecs } from '@/lib/openapi'
|
|
3
|
+
|
|
4
|
+
export async function handleApisProxy(req: Request): Promise<Response> {
|
|
5
|
+
if (req.method !== 'POST') {
|
|
6
|
+
return Response.json({ error: 'Method not allowed' }, { status: 405 })
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const { specName, method, path, headers, body } = await req.json()
|
|
10
|
+
|
|
11
|
+
if (!specName || !method || !path) {
|
|
12
|
+
return Response.json({ error: 'Missing specName, method, or path' }, { status: 400 })
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const config = loadConfig()
|
|
16
|
+
const specs = loadApiSpecs(config.api ?? [])
|
|
17
|
+
const spec = specs.find((s) => s.name === specName)
|
|
18
|
+
|
|
19
|
+
if (!spec) {
|
|
20
|
+
return Response.json({ error: `Unknown spec: ${specName}` }, { status: 404 })
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const url = spec.server.url + path
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
const response = await fetch(url, {
|
|
27
|
+
method,
|
|
28
|
+
headers,
|
|
29
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
const contentType = response.headers.get('content-type') ?? ''
|
|
33
|
+
const responseBody = contentType.includes('application/json')
|
|
34
|
+
? await response.json()
|
|
35
|
+
: await response.text()
|
|
36
|
+
|
|
37
|
+
return Response.json({
|
|
38
|
+
status: response.status,
|
|
39
|
+
statusText: response.statusText,
|
|
40
|
+
body: responseBody,
|
|
41
|
+
}, { status: response.status })
|
|
42
|
+
} catch (error) {
|
|
43
|
+
const message = error instanceof Error
|
|
44
|
+
? `${error.message}${error.cause ? `: ${(error.cause as Error).message}` : ''}`
|
|
45
|
+
: 'Request failed'
|
|
46
|
+
return Response.json({
|
|
47
|
+
status: 502,
|
|
48
|
+
statusText: 'Bad Gateway',
|
|
49
|
+
body: `Could not reach ${url}\n${message}`,
|
|
50
|
+
}, { status: 502 })
|
|
51
|
+
}
|
|
52
|
+
}
|