feat: 发布 v0.4.0 桌面端

This commit is contained in:
SkyJourney
2026-07-27 20:56:39 +08:00
parent 92a5bfd016
commit 4d60741f5a
90 changed files with 10431 additions and 223 deletions
+1
View File
@@ -11,6 +11,7 @@
"typecheck": "tsc -p tsconfig.json --noEmit --pretty false"
},
"dependencies": {
"@md-to-pdf/application": "0.4.0",
"@md-to-pdf/core": "0.1.0",
"@md-to-pdf/renderer": "0.1.0",
"fastify": "^5.6.2",
+44 -121
View File
@@ -10,10 +10,11 @@ import {
supportedPaperFormats
} from "@md-to-pdf/core";
import {
MarkdownDocumentParseError,
RENDERER_VERSION,
renderMarkdown
} from "@md-to-pdf/renderer";
ApplicationRequestError,
createApplicationService,
type ApplicationService
} from "@md-to-pdf/application";
import { RENDERER_VERSION } from "@md-to-pdf/renderer";
import {
createPdfGenerator,
PdfEngineClosedError,
@@ -21,7 +22,6 @@ import {
PdfRenderTimeoutError,
type PdfGenerator
} from "./pdf-engine.js";
import { createThemeRegistry } from "./theme-registry.js";
interface RenderRequestBody {
markdown?: unknown;
@@ -34,66 +34,6 @@ interface PdfRequestBody extends RenderRequestBody {
}
const projectRoot = fileURLToPath(new URL("../../../", import.meta.url));
const maximumMarkdownLength = 1_500_000;
function validateMarkdownRequest(
body: RenderRequestBody | undefined
):
| { markdown: string; language?: string }
| { statusCode: 400 | 413; error: string; message: string } {
const { markdown, language } = body ?? {};
if (typeof markdown !== "string") {
return {
statusCode: 400,
error: "INVALID_MARKDOWN",
message: "markdown 必须是字符串"
};
}
if (markdown.length > maximumMarkdownLength) {
return {
statusCode: 413,
error: "MARKDOWN_TOO_LARGE",
message: "Markdown 内容不能超过 1.5 MB"
};
}
if (language !== undefined && typeof language !== "string") {
return {
statusCode: 400,
error: "INVALID_LANGUAGE",
message: "language 必须是字符串"
};
}
return {
markdown,
...(typeof language === "string" ? { language } : {})
};
}
function renderMarkdownRequest(
markdown: string,
language: string | undefined
) {
try {
return {
success: true as const,
document: renderMarkdown(markdown, {
...(language ? { language } : {})
})
};
} catch (error) {
if (error instanceof MarkdownDocumentParseError) {
return {
success: false as const,
error: error.code,
message: error.message
};
}
throw error;
}
}
function encodeRfc5987(value: string) {
return encodeURIComponent(value).replace(
/[!'()*]/g,
@@ -127,6 +67,7 @@ export interface BuildAppOptions {
logger?: boolean;
pdfGenerator?: PdfGenerator;
prewarmPdfBrowser?: boolean;
applicationService?: ApplicationService;
}
function milliseconds(value: number) {
@@ -169,12 +110,14 @@ export function buildApp(options: BuildAppOptions = {}) {
logger: options.logger ?? true,
bodyLimit: 2 * 1024 * 1024
});
const themes = createThemeRegistry({
bundledRoot: resolve(projectRoot, "themes"),
localRoot:
options.localThemeRoot ?? resolve(projectRoot, ".local", "themes"),
onWarning: (message) => app.log.warn(message)
});
const applicationService =
options.applicationService ??
createApplicationService({
bundledRoot: resolve(projectRoot, "themes"),
localRoot:
options.localThemeRoot ?? resolve(projectRoot, ".local", "themes"),
onWarning: (message) => app.log.warn(message)
});
const pdfGenerator =
options.pdfGenerator ?? createPdfGenerator();
@@ -213,23 +156,16 @@ export function buildApp(options: BuildAppOptions = {}) {
planned: []
}));
app.get("/api/themes", async () => ({
themes: (await themes.list()).map(({ manifest, source }) => ({
id: manifest.id,
name: manifest.name,
version: manifest.version,
description: manifest.description,
bundled: manifest.bundled,
source
}))
}));
app.get("/api/themes", async () =>
applicationService.listThemes()
);
app.get<{ Params: { themeId: string } }>(
"/api/themes/:themeId/css",
async (request, reply) => {
const { themeId } = request.params;
const css = await themes.getCss(themeId);
const css = await applicationService.getThemeCss(themeId);
if (css === undefined) {
return reply.code(404).send({
error: "THEME_NOT_FOUND",
@@ -248,7 +184,7 @@ export function buildApp(options: BuildAppOptions = {}) {
"/api/themes/:themeId/assets/*",
async (request, reply) => {
try {
const asset = await themes.getAsset(
const asset = await applicationService.getThemeAsset(
request.params.themeId,
request.params["*"]
);
@@ -277,25 +213,17 @@ export function buildApp(options: BuildAppOptions = {}) {
app.post<{ Body: RenderRequestBody }>(
"/api/render",
async (request, reply) => {
const validated = validateMarkdownRequest(request.body);
if ("statusCode" in validated) {
return reply.code(validated.statusCode).send({
error: validated.error,
message: validated.message
});
try {
return applicationService.render(request.body ?? {});
} catch (error) {
if (error instanceof ApplicationRequestError) {
return reply.code(error.statusCode).send({
error: error.code,
message: error.message
});
}
throw error;
}
const rendered = renderMarkdownRequest(
validated.markdown,
validated.language
);
if (!rendered.success) {
return reply.code(400).send({
error: rendered.error,
message: rendered.message
});
}
return rendered.document;
}
);
@@ -303,14 +231,6 @@ export function buildApp(options: BuildAppOptions = {}) {
"/api/pdf",
async (request, reply) => {
const requestStartedAt = performance.now();
const validated = validateMarkdownRequest(request.body);
if ("statusCode" in validated) {
return reply.code(validated.statusCode).send({
error: validated.error,
message: validated.message
});
}
const parsedConfig = exportConfigSchema.safeParse(
request.body?.exportConfig
);
@@ -333,7 +253,9 @@ export function buildApp(options: BuildAppOptions = {}) {
}
const themeStartedAt = performance.now();
const themeCss = await themes.getCss(parsedConfig.data.themeId);
const themeCss = await applicationService.getThemeCss(
parsedConfig.data.themeId
);
const themeMs = performance.now() - themeStartedAt;
if (themeCss === undefined) {
return reply.code(404).send({
@@ -343,18 +265,19 @@ export function buildApp(options: BuildAppOptions = {}) {
}
const markdownStartedAt = performance.now();
const renderedResult = renderMarkdownRequest(
validated.markdown,
validated.language
);
const markdownMs = performance.now() - markdownStartedAt;
if (!renderedResult.success) {
return reply.code(400).send({
error: renderedResult.error,
message: renderedResult.message
});
let rendered;
try {
rendered = applicationService.render(request.body ?? {});
} catch (error) {
if (error instanceof ApplicationRequestError) {
return reply.code(error.statusCode).send({
error: error.code,
message: error.message
});
}
throw error;
}
const rendered = renderedResult.document;
const markdownMs = performance.now() - markdownStartedAt;
try {
const generated = await pdfGenerator.generate(
-381
View File
@@ -1,381 +0,0 @@
import {
readdir,
readFile,
realpath,
stat
} from "node:fs/promises";
import {
extname,
isAbsolute,
posix,
relative,
resolve,
sep
} from "node:path";
import {
themeManifestSchema,
type ThemeManifest
} from "@md-to-pdf/core";
export interface ThemeRecord {
manifest: ThemeManifest;
directory: string;
source: "bundled" | "local";
}
export interface ThemeRegistryOptions {
bundledRoot: string;
localRoot: string;
onWarning?: (message: string) => void;
cacheTtlMs?: number;
}
const assetContentTypes: Record<string, string> = {
".gif": "image/gif",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".svg": "image/svg+xml",
".ttf": "font/ttf",
".webp": "image/webp",
".woff": "font/woff",
".woff2": "font/woff2"
};
const cssImportPattern =
/@import\s+(?:url\(\s*(?:\"([^\"]+)\"|'([^']+)'|([^'\"\s)]+))\s*\)|\"([^\"]+)\"|'([^']+)')\s*;/gi;
const maximumCssImportDepth = 8;
function isMissingFileError(error: unknown) {
return (
error instanceof Error &&
"code" in error &&
(error as NodeJS.ErrnoException).code === "ENOENT"
);
}
function isInsideDirectory(directory: string, path: string) {
const pathFromDirectory = relative(directory, path);
return (
pathFromDirectory === "" ||
(!pathFromDirectory.startsWith(`..${sep}`) &&
pathFromDirectory !== ".." &&
!isAbsolute(pathFromDirectory))
);
}
async function resolveThemeFile(directory: string, relativePath: string) {
if (
isAbsolute(relativePath) ||
relativePath.includes("\0") ||
relativePath.split(/[\\/]/).includes("..")
) {
throw new Error("主题资源路径不安全");
}
const realDirectory = await realpath(directory);
const candidate = resolve(realDirectory, relativePath);
if (!isInsideDirectory(realDirectory, candidate)) {
throw new Error("主题资源路径越界");
}
const realCandidate = await realpath(candidate);
if (!isInsideDirectory(realDirectory, realCandidate)) {
throw new Error("主题资源符号链接越界");
}
const fileStat = await stat(realCandidate);
if (!fileStat.isFile()) {
throw new Error("主题资源不是文件");
}
return realCandidate;
}
async function readThemeRoot(
root: string,
source: ThemeRecord["source"],
onWarning?: (message: string) => void
): Promise<ThemeRecord[]> {
let entries;
try {
entries = await readdir(root, { withFileTypes: true });
} catch (error) {
if (isMissingFileError(error) && source === "local") {
return [];
}
throw error;
}
const records: ThemeRecord[] = [];
for (const entry of entries) {
if (!entry.isDirectory()) {
continue;
}
const directory = resolve(root, entry.name);
try {
const manifestPath = await resolveThemeFile(directory, "theme.json");
const manifest = themeManifestSchema.parse(
JSON.parse(await readFile(manifestPath, "utf8"))
);
if (manifest.id !== entry.name) {
throw new Error("主题目录名必须与主题 ID 一致");
}
if (manifest.bundled !== (source === "bundled")) {
throw new Error("主题 bundled 标记与来源不一致");
}
if (manifest.base) {
await resolveThemeFile(directory, manifest.base);
}
await resolveThemeFile(directory, manifest.entry);
if (manifest.print) {
await resolveThemeFile(directory, manifest.print);
}
records.push({
manifest,
directory,
source
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (source === "local") {
onWarning?.(`已忽略无效本地主题 ${entry.name}${message}`);
continue;
}
throw new Error(`主题 ${entry.name} 无效:${message}`);
}
}
return records;
}
function encodeAssetPath(path: string) {
return path
.split("/")
.map((segment) => encodeURIComponent(segment))
.join("/");
}
function prepareCssSegment(
css: string,
themeId: string,
cssDirectory: string
) {
return css.replace(
/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi,
(match, _quote: string, rawValue: string) => {
const value = rawValue.trim();
if (value.startsWith("data:") || value.startsWith("#")) {
return match;
}
if (
value.startsWith("/") ||
value.startsWith("//") ||
/^[a-z][a-z0-9+.-]*:/i.test(value)
) {
throw new Error(`主题包含不允许的外部资源:${value}`);
}
const normalized = value.replaceAll("\\", "/").replace(/^\.\//, "");
if (normalized.split("/").includes("..")) {
throw new Error(`主题资源路径不安全:${value}`);
}
const assetPath = posix.normalize(posix.join(cssDirectory, normalized));
if (
assetPath === ".." ||
assetPath.startsWith("../") ||
assetPath.startsWith("/")
) {
throw new Error(`主题资源路径越界:${value}`);
}
return `url("/api/themes/${encodeURIComponent(themeId)}/assets/${encodeAssetPath(assetPath)}")`;
}
);
}
function readImportedPath(match: RegExpMatchArray) {
return match.slice(1).find((value): value is string => value !== undefined);
}
function normalizeCssPath(relativePath: string) {
const normalized = relativePath.replaceAll("\\", "/");
if (
normalized.startsWith("/") ||
normalized.split("/").includes("..") ||
/^[a-z][a-z0-9+.-]*:/i.test(normalized)
) {
throw new Error(`主题 CSS 路径不安全:${relativePath}`);
}
return posix.normalize(normalized.replace(/^\.\//, ""));
}
async function loadThemeCssFile(
theme: ThemeRecord,
relativePath: string,
importStack: string[] = []
): Promise<string> {
const normalizedPath = normalizeCssPath(relativePath);
if (importStack.includes(normalizedPath)) {
throw new Error(
`主题 CSS 存在循环引用:${[...importStack, normalizedPath].join(" -> ")}`
);
}
if (importStack.length >= maximumCssImportDepth) {
throw new Error(`主题 CSS 导入层级超过 ${maximumCssImportDepth}`);
}
const cssPath = await resolveThemeFile(theme.directory, normalizedPath);
const css = (await readFile(cssPath, "utf8")).replace(
/^\s*@include-when-export\s+url\([^;\r\n]+;\s*$/gim,
""
);
const cssDirectory = posix.dirname(normalizedPath);
const matches = [...css.matchAll(cssImportPattern)];
let result = "";
let previousEnd = 0;
for (const match of matches) {
const matchStart = match.index ?? 0;
result += prepareCssSegment(
css.slice(previousEnd, matchStart),
theme.manifest.id,
cssDirectory
);
const importedPath = readImportedPath(match);
if (!importedPath) {
throw new Error(`无法解析主题 CSS 导入:${match[0]}`);
}
const normalizedImport = normalizeCssPath(importedPath);
const importPath = posix.normalize(posix.join(cssDirectory, normalizedImport));
result += await loadThemeCssFile(theme, importPath, [
...importStack,
normalizedPath
]);
previousEnd = matchStart + match[0].length;
}
const remainder = css.slice(previousEnd);
result += prepareCssSegment(
remainder,
theme.manifest.id,
cssDirectory
);
if (/@import\b/i.test(result)) {
throw new Error("主题包含不支持的 CSS @import 语法");
}
return result;
}
export function createThemeRegistry(options: ThemeRegistryOptions) {
const cacheTtlMs = options.cacheTtlMs ?? 1_000;
if (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0) {
throw new Error("主题缓存有效期必须是非负有限数值");
}
let cachedThemes:
| {
expiresAt: number;
promise: Promise<ThemeRecord[]>;
}
| undefined;
async function scanThemes() {
const [bundledThemes, localThemes] = await Promise.all([
readThemeRoot(options.bundledRoot, "bundled"),
readThemeRoot(options.localRoot, "local", options.onWarning)
]);
const themes = [...bundledThemes, ...localThemes];
const themeIds = new Set<string>();
for (const theme of themes) {
if (themeIds.has(theme.manifest.id)) {
throw new Error(`主题 ID 重复:${theme.manifest.id}`);
}
themeIds.add(theme.manifest.id);
}
return themes;
}
function list() {
const now = Date.now();
if (cachedThemes && now < cachedThemes.expiresAt) {
return cachedThemes.promise;
}
const promise = scanThemes();
cachedThemes = {
expiresAt: now + cacheTtlMs,
promise
};
void promise.catch(() => {
if (cachedThemes?.promise === promise) {
cachedThemes = undefined;
}
});
return promise;
}
function invalidate() {
cachedThemes = undefined;
}
async function get(themeId: string) {
return (await list()).find((theme) => theme.manifest.id === themeId);
}
async function getCss(themeId: string) {
const theme = await get(themeId);
if (!theme) {
return undefined;
}
const cssFiles = [
...(theme.manifest.base ? [theme.manifest.base] : []),
theme.manifest.entry,
...(theme.manifest.print
? [theme.manifest.print]
: [])
];
return (
await Promise.all(
cssFiles.map((path) => loadThemeCssFile(theme, path))
)
).join("\n");
}
async function getAsset(themeId: string, assetPath: string) {
const theme = await get(themeId);
if (!theme) {
return undefined;
}
const extension = extname(assetPath).toLowerCase();
const contentType = assetContentTypes[extension];
if (!contentType) {
throw new Error("不支持的主题资源类型");
}
const path = await resolveThemeFile(theme.directory, assetPath);
return {
contentType,
content: await readFile(path)
};
}
return {
get,
getAsset,
getCss,
invalidate,
list
};
}
+1 -1
View File
@@ -8,7 +8,7 @@ import {
createPdfContentDisposition,
createPdfFileName
} from "../src/app.js";
import { createThemeRegistry } from "../src/theme-registry.js";
import { createThemeRegistry } from "@md-to-pdf/application";
import {
PdfEngineOverloadedError,
type PdfGenerator