XWX-AI Claude Opus 4.6 commited on
Commit
e14f86d
·
1 Parent(s): cd363bd

v1.4.6 代码块高亮最终方案 - Shiki 后端预高亮

Browse files

- 添加 shiki 依赖,启动时初始化 103 种语言高亮
- 实现三路语法高亮选择逻辑:
1. codeTheme 有值 → Shiki 预高亮(新插件)
2. codeTheme 为空 + HTML 含 highlight.js CDN → legacy 路径(旧插件)
3. codeTheme 为空 + 无 CDN → Shiki 默认 github-light(兜底)
- 支持三种 codeTheme 映射:
github→github-light, monokai→monokai, oneDark→one-dark-pro
- 向后兼容:旧版本插件不受影响

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Files changed (2) hide show
  1. package.json +2 -1
  2. server.js +103 -6
package.json CHANGED
@@ -5,9 +5,10 @@
5
  "description": "Puppeteer PDF Generator for Hugging Face Spaces",
6
  "main": "server.js",
7
  "dependencies": {
 
8
  "express": "^4.18.2",
9
  "puppeteer": "^22.0.0",
10
- "cors": "^2.8.5"
11
  },
12
  "scripts": {
13
  "start": "node server.js"
 
5
  "description": "Puppeteer PDF Generator for Hugging Face Spaces",
6
  "main": "server.js",
7
  "dependencies": {
8
+ "cors": "^2.8.5",
9
  "express": "^4.18.2",
10
  "puppeteer": "^22.0.0",
11
+ "shiki": "^1.24.0"
12
  },
13
  "scripts": {
14
  "start": "node server.js"
server.js CHANGED
@@ -25,6 +25,84 @@
25
  const express = require('express');
26
  const puppeteer = require('puppeteer');
27
  const cors = require('cors');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  const app = express();
30
  const port = process.env.PORT || 7860;
@@ -61,11 +139,30 @@ app.post('/api/generate_pdf', async (req, res) => {
61
  let browser = null;
62
 
63
  try {
64
- const { html, showWatermark, imageCount, totalImageSizeMB } = req.body;
65
  if (!html) {
66
  return res.status(400).json({ error: 'Missing html content' });
67
  }
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  const brandText = showWatermark !== false ? 'Powered by XWX AI Chat Exporter' : '';
70
  const htmlSizeMB = (html.length / 1024 / 1024).toFixed(2);
71
  const imgCount = imageCount || 0;
@@ -76,11 +173,11 @@ app.post('/api/generate_pdf', async (req, res) => {
76
  // 关键修复:移除所有图片的 loading="lazy" 属性
77
  // 问题:loading="lazy" 导致视口外的图片在 PDF 中不渲染
78
  // 解决方案:https://stackoverflow.com/questions/79156691/puppeteersharp-fails-to-display-base64-encoded-images-in-pdf-output
79
- const htmlWithoutLazy = html.replace(/loading=["']lazy["']/gi, '');
80
  console.log(`[PDF-GEN] [${getElapsed()}] 已移除 loading="lazy" 属性`);
81
-
82
- // 使用移除 lazy 后的 HTML
83
- const htmlToUse = htmlWithoutLazy;
84
 
85
  const baseWaitTime = imgCount > 0 ? Math.min(500 + imgCount * 400, 6000) : 500;
86
  const sizeWaitTime = imgSizeMB > 0 ? Math.min(imgSizeMB * 100, 3000) : 0;
@@ -128,7 +225,7 @@ app.post('/api/generate_pdf', async (req, res) => {
128
  // 设置 viewport 满足大部分页面渲染需求
129
  await page.setViewport({ width: 1200, height: 800 });
130
  console.log(`[PDF-GEN] [${getElapsed()}] Viewport: 1200x800`);
131
-
132
  console.log(`[PDF-GEN] [${getElapsed()}] 正在填充页面内容...`);
133
  await page.setContent(htmlToUse, {
134
  waitUntil: ['load', 'networkidle0'],
 
25
  const express = require('express');
26
  const puppeteer = require('puppeteer');
27
  const cors = require('cors');
28
+ const { getHighlighter } = require('shiki');
29
+
30
+ // ─── Shiki Highlighter Initialization ─────────────────
31
+ // Maps frontend codeTheme settings to Shiki theme names
32
+ const THEME_MAP = {
33
+ 'github': 'github-light',
34
+ 'monokai': 'monokai',
35
+ 'oneDark': 'one-dark-pro',
36
+ };
37
+
38
+ let shikiHighlighter = null;
39
+
40
+ async function initShiki() {
41
+ try {
42
+ console.log('[Shiki] Initializing highlighter with bundled languages...');
43
+ shikiHighlighter = await getHighlighter({
44
+ themes: ['github-light', 'monokai', 'one-dark-pro'],
45
+ langs: [
46
+ // Core languages (all included in shiki default bundle)
47
+ 'javascript', 'typescript', 'python', 'java', 'c', 'cpp', 'csharp',
48
+ 'go', 'rust', 'ruby', 'php', 'swift', 'kotlin', 'sql', 'bash',
49
+ 'shell', 'yaml', 'json', 'html', 'xml', 'css', 'scss', 'less',
50
+ 'markdown', 'diff', 'dockerfile', 'lua', 'r', 'dart', 'scala',
51
+ // Additional languages
52
+ 'perl', 'haskell', 'erlang', 'elixir', 'clojure', 'groovy',
53
+ 'objective-c', 'asm', 'powershell', 'makefile', 'cmake',
54
+ 'protobuf', 'graphql', 'toml', 'ini', 'git-rebase',
55
+ // Rare languages (verified in shiki default bundle)
56
+ 'abap', 'cobol', 'pascal', 'racket', 'latex', 'tex',
57
+ 'viml', 'nginx', 'apache', 'vue', 'svelte', 'zig',
58
+ 'matlab', 'julia', 'astro',
59
+ ],
60
+ });
61
+ const langs = shikiHighlighter.getLoadedLanguages();
62
+ console.log(`[Shiki] Highlighter ready with ${langs.length} languages: ${langs.slice(0, 20).join(', ')}...`);
63
+ } catch (e) {
64
+ console.error('[Shiki] Failed to initialize:', e.message);
65
+ shikiHighlighter = null;
66
+ }
67
+ }
68
+
69
+ // Pre-highlight code blocks in HTML using Shiki (inline styles)
70
+ function highlightHtmlWithShiki(html, themeName = 'github-light') {
71
+ if (!shikiHighlighter) return html;
72
+
73
+ const shikiTheme = THEME_MAP[themeName] || 'github-light';
74
+
75
+ return html.replace(/<pre([^>]*)><code[^>]*>([\s\S]*?)<\/code><\/pre>/gi, (match, preAttrs, codeText) => {
76
+ // Skip if already has syntax spans (Shiki-style or hljs-style)
77
+ if (/<span/i.test(codeText)) return match;
78
+
79
+ // Extract language from class or data attribute
80
+ let lang = '';
81
+ const classMatch = preAttrs.match(/class="[^"]*language-(\w+)/i)
82
+ || preAttrs.match(/data-language="(\w+)"/i);
83
+ if (classMatch) lang = classMatch[1].toLowerCase();
84
+
85
+ // Try Shiki highlight
86
+ if (lang && shikiHighlighter.getLoadedLanguages().includes(lang)) {
87
+ try {
88
+ const highlighted = shikiHighlighter.codeToHtml(codeText
89
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"'),
90
+ { lang, theme: shikiTheme }
91
+ );
92
+ return highlighted;
93
+ } catch (e) {
94
+ // Fallback to plain pre
95
+ }
96
+ }
97
+
98
+ return match;
99
+ });
100
+ }
101
+
102
+ // Start Shiki initialization (non-blocking)
103
+ initShiki().then(() => {
104
+ console.log('[Shiki] Startup initialization complete.');
105
+ }).catch(() => {});
106
 
107
  const app = express();
108
  const port = process.env.PORT || 7860;
 
139
  let browser = null;
140
 
141
  try {
142
+ const { html, showWatermark, imageCount, totalImageSizeMB, codeTheme } = req.body;
143
  if (!html) {
144
  return res.status(400).json({ error: 'Missing html content' });
145
  }
146
 
147
+ // ─── Syntax Highlighting Path Selection ───
148
+ // Priority: codeTheme param > HTML detection > Shiki default
149
+ // 1. If codeTheme is sent (new plugin) → always use Shiki
150
+ // 2. If no codeTheme → check for highlight.js script in HTML
151
+ // - Found → legacy highlight.js path (old plugin)
152
+ // - Not found → Shiki default (no highlighting in HTML)
153
+ const hasHighlightJsScript = html.includes('highlight.min.js') || html.includes('highlight.full.min.js') || html.includes('hljs.highlightAll');
154
+ let htmlToProcess = html;
155
+
156
+ if (codeTheme) {
157
+ console.log(`[PDF-GEN] [${getElapsed()}] codeTheme provided (${codeTheme}), using Shiki`);
158
+ htmlToProcess = highlightHtmlWithShiki(html, codeTheme);
159
+ } else if (hasHighlightJsScript && shikiHighlighter) {
160
+ console.log(`[PDF-GEN] [${getElapsed()}] No codeTheme, detected highlight.js in HTML, using legacy path`);
161
+ } else if (shikiHighlighter) {
162
+ console.log(`[PDF-GEN] [${getElapsed()}] No codeTheme, no highlight.js, using Shiki default`);
163
+ htmlToProcess = highlightHtmlWithShiki(html, 'github');
164
+ }
165
+
166
  const brandText = showWatermark !== false ? 'Powered by XWX AI Chat Exporter' : '';
167
  const htmlSizeMB = (html.length / 1024 / 1024).toFixed(2);
168
  const imgCount = imageCount || 0;
 
173
  // 关键修复:移除所有图片的 loading="lazy" 属性
174
  // 问题:loading="lazy" 导致视口外的图片在 PDF 中不渲染
175
  // 解决方案:https://stackoverflow.com/questions/79156691/puppeteersharp-fails-to-display-base64-encoded-images-in-pdf-output
176
+ htmlToProcess = htmlToProcess.replace(/loading=["']lazy["']/gi, '');
177
  console.log(`[PDF-GEN] [${getElapsed()}] 已移除 loading="lazy" 属性`);
178
+
179
+ // 使用处理后的 HTML
180
+ const htmlToUse = htmlToProcess;
181
 
182
  const baseWaitTime = imgCount > 0 ? Math.min(500 + imgCount * 400, 6000) : 500;
183
  const sizeWaitTime = imgSizeMB > 0 ? Math.min(imgSizeMB * 100, 3000) : 0;
 
225
  // 设置 viewport 满足大部分页面渲染需求
226
  await page.setViewport({ width: 1200, height: 800 });
227
  console.log(`[PDF-GEN] [${getElapsed()}] Viewport: 1200x800`);
228
+
229
  console.log(`[PDF-GEN] [${getElapsed()}] 正在填充页面内容...`);
230
  await page.setContent(htmlToUse, {
231
  waitUntil: ['load', 'networkidle0'],