feat(server): add content-type map for preview-fs static route

Implement a pure function that maps file extensions to their correct MIME types,
supporting common web assets (HTML, CSS, JS, JSON, images, fonts) with proper
charset declarations and fallback to application/octet-stream.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
程序员阿江(Relakkes) 2026-05-29 12:27:51 +08:00
parent 3077f1569d
commit a0d5e7c40c
2 changed files with 42 additions and 0 deletions

View File

@ -0,0 +1,16 @@
import { describe, expect, it } from 'bun:test'
import { contentTypeForPath } from '../previewFs'
describe('contentTypeForPath', () => {
it('maps common web asset extensions', () => {
expect(contentTypeForPath('/x/index.html')).toBe('text/html; charset=utf-8')
expect(contentTypeForPath('/x/app.css')).toBe('text/css; charset=utf-8')
expect(contentTypeForPath('/x/app.js')).toBe('text/javascript; charset=utf-8')
expect(contentTypeForPath('/x/data.json')).toBe('application/json; charset=utf-8')
expect(contentTypeForPath('/x/logo.svg')).toBe('image/svg+xml')
expect(contentTypeForPath('/x/p.png')).toBe('image/png')
})
it('falls back to octet-stream for unknown', () => {
expect(contentTypeForPath('/x/file.bin')).toBe('application/octet-stream')
})
})

View File

@ -0,0 +1,26 @@
import * as path from 'node:path'
const CONTENT_TYPES: Record<string, string> = {
html: 'text/html; charset=utf-8',
htm: 'text/html; charset=utf-8',
css: 'text/css; charset=utf-8',
js: 'text/javascript; charset=utf-8',
mjs: 'text/javascript; charset=utf-8',
json: 'application/json; charset=utf-8',
svg: 'image/svg+xml',
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
webp: 'image/webp',
ico: 'image/x-icon',
woff: 'font/woff',
woff2: 'font/woff2',
txt: 'text/plain; charset=utf-8',
md: 'text/plain; charset=utf-8',
}
export function contentTypeForPath(filePath: string): string {
const ext = path.extname(filePath).slice(1).toLowerCase()
return CONTENT_TYPES[ext] ?? 'application/octet-stream'
}