dsh-pdf-workbench 1.4.1 → 1.5.0
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/README.md +29 -7
- package/client.js +4106 -469
- package/docs/LAYOUT.md +56 -0
- package/docs/RELEASE.md +8 -0
- package/docs/TESTING.md +16 -0
- package/docs/ci.md +18 -13
- package/docs/copy/templates.md +4 -4
- package/docs/decisions.md +119 -0
- package/docs/features.md +14 -8
- package/docs/requirements/2026-11-25-v1.5/346/224/271/350/277/233/351/234/200/346/261/202.md +622 -0
- package/docs/roles/{release-manager.md → ci.md} +37 -47
- package/docs/roles/programmer.md +45 -59
- package/docs/roles/requirements.md +68 -0
- package/docs/todo.md +590 -32
- package/index.js +337 -1
- package/package.json +1 -1
- package/src/host/backup.js +172 -33
- package/src/host/book-wizard.js +454 -0
- package/src/host/digest.js +4 -0
- package/src/host/engine.js +88 -0
- package/src/host/exports.js +159 -0
- package/src/host/http.js +28 -1
- package/src/host/imports.js +650 -0
- package/src/host/index-source.js +117 -11
- package/src/host/library-export.js +162 -0
- package/src/host/pdf-source.js +6 -2
- package/src/host/routes.js +1020 -120
- package/src/host/shortcut.js +238 -0
- package/src/host/storage.js +421 -0
- package/src/host/translate-blocks.js +49 -45
- package/src/host/translate-job.js +37 -10
- package/src/host/translate.js +19 -45
- package/src/host/translation-cache.js +209 -0
- package/src/host/typst-install.js +132 -0
- package/src/host/zip.js +486 -4
- package/tools/latex_to_typst.py +1353 -0
- package/tools/md2overlay.py +147 -152
- package/tools/md2overlay_typst.py +312 -0
- package/tools/md2typst.py +818 -0
- package/tools/overlay_layout.py +332 -0
- package/tools/pdf_blocks.py +82 -10
- package/tools/realign_overlay.py +4 -1
- package/tools/rebuild_overlay.py +3 -1
- package/tools/split_pdf.py +158 -0
- package/tools/typst_runtime.py +98 -0
- package/vendor/katex/LICENSE +21 -0
- package/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
- package/vendor/katex/katex.min.css +1 -0
- package/vendor/katex/katex.min.js +1 -0
- package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +9 -1
- package/docs/boss-handover.md +0 -84
- package/docs/roles/auditor.md +0 -123
- package/docs/roles/boss.md +0 -162
- package/docs/roles/code-reviewer.md +0 -132
- package/docs/roles/feature-inventory.md +0 -119
- package/docs/roles/feedback-collector.md +0 -105
- package/docs/roles/tester.md +0 -140
- package/docs/roles/ui-copywriter.md +0 -122
- package/src/host/book-import.js +0 -98
package/src/host/routes.js
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
* GET /pdfdesk/questions one chapter's page-mark questions
|
|
12
12
|
* PUT /pdfdesk/questions replace one chapter's questions
|
|
13
13
|
* POST /pdfdesk/print-page one Markdown product as a printable HTML page
|
|
14
|
+
* POST /pdfdesk/imports the one import pipeline (PDF, md/txt, book ZIP, migration ZIP)
|
|
15
|
+
* POST /pdfdesk/library-export one library's data (index, .pdfdesk, optional artifacts; no PDFs) as a ZIP
|
|
14
16
|
* POST /pdfdesk/digest summarize a chapter's conversations
|
|
15
17
|
* GET /pdfdesk/vendor/<file> the reader's pdf.js build
|
|
16
18
|
* POST /pdfdesk/links attach an existing session to a chapter
|
|
@@ -28,7 +30,7 @@ import { execFile } from 'node:child_process'
|
|
|
28
30
|
import { randomUUID } from 'node:crypto'
|
|
29
31
|
import { tmpdir } from 'node:os'
|
|
30
32
|
import { existsSync } from 'node:fs'
|
|
31
|
-
import { copyFile, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises'
|
|
33
|
+
import { copyFile, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from 'node:fs/promises'
|
|
32
34
|
import { basename, dirname, extname, isAbsolute, join, relative } from 'node:path'
|
|
33
35
|
|
|
34
36
|
import { chapterArtifactDir, countArtifacts, listArtifacts, readArtifact, resolveChapter } from './artifacts.js'
|
|
@@ -41,12 +43,17 @@ import { addAttachment, attachmentsDir, listAttachments, MAX_ATTACHMENT_BYTES, r
|
|
|
41
43
|
import { convertPptToPdf, isPptPath, pdfNameForPpt } from './ppt.js'
|
|
42
44
|
import { MAX_FONT_BYTES, downloadFont, fontStatus, installFont, readFont, removeFont } from './fonts.js'
|
|
43
45
|
import { createBackup, importBackup, readBackup } from './backup.js'
|
|
44
|
-
import {
|
|
46
|
+
import { isExportName, listExports, listJobs, revealDirectory, revealInFileManager, startExportJob } from './exports.js'
|
|
47
|
+
import { exportLibrary, exportPdfPack } from './library-export.js'
|
|
48
|
+
import { checkArchiveFile, importArchive, importSingle, MAX_ARCHIVE_FILE_BYTES, MAX_ARCHIVE_TOTAL_BYTES, MAX_UPLOAD_BYTES, receiveUpload, RejectError } from './imports.js'
|
|
49
|
+
import { applyBookPack, discardStage, inspectBookPack } from './book-wizard.js'
|
|
45
50
|
import { markdownToHtml, printPageHtml } from './print.js'
|
|
46
51
|
import { PLUGIN_VERSION } from './config.js'
|
|
47
|
-
import { fail, isLoopback, isSameOrigin, readJson, sendBytes, sendJson } from './http.js'
|
|
52
|
+
import { fail, isLoopback, isSameOrigin, readJson, sendBytes, sendJson, sendNotModified } from './http.js'
|
|
53
|
+
import { installTypst, installed, TYPST_VERSION } from './typst-install.js'
|
|
48
54
|
import { loadCatalog } from './index-source.js'
|
|
49
55
|
import { readPageBlocks } from './blocks.js'
|
|
56
|
+
import { chapterCacheDir, legacyTranslationRoot, translationRoot } from './translation-cache.js'
|
|
50
57
|
import { translatePage } from './translate.js'
|
|
51
58
|
import { startChapterJob } from './translate-job.js'
|
|
52
59
|
import { artifactPdfPath, chapterPdfPath } from './pdf-source.js'
|
|
@@ -55,6 +62,7 @@ import { checkForUpdate } from './update.js'
|
|
|
55
62
|
import { detectEnvironment } from './environment.js'
|
|
56
63
|
import { renderMarkdown } from './render.js'
|
|
57
64
|
import { readState, writeState } from './state.js'
|
|
65
|
+
import { cleanTemporary, emptyTrash, measureStorage, pruneStaleJobs, pruneTranslationIdle, pruneTrash, scanDuplicates } from './storage.js'
|
|
58
66
|
|
|
59
67
|
/** Route prefix owned by this plugin. */
|
|
60
68
|
export const PREFIX = '/pdfdesk'
|
|
@@ -72,6 +80,12 @@ function vendorContentType(name) {
|
|
|
72
80
|
if (name === 'fonts/zhhand/OFL.txt') return 'text/plain; charset=utf-8'
|
|
73
81
|
if (/^rough\/[^/]+\.mjs$/.test(name)) return 'text/javascript; charset=utf-8'
|
|
74
82
|
if (name === 'rough/LICENSE') return 'text/plain; charset=utf-8'
|
|
83
|
+
// KaTeX renders the overlay text layer's formulas; only the browser build and
|
|
84
|
+
// the woff2 subsets are vendored (the .woff/.ttf fallbacks are not served).
|
|
85
|
+
if (name === 'katex/katex.min.js') return 'text/javascript; charset=utf-8'
|
|
86
|
+
if (name === 'katex/katex.min.css') return 'text/css; charset=utf-8'
|
|
87
|
+
if (/^katex\/fonts\/[A-Za-z0-9._-]+\.woff2$/.test(name)) return 'font/woff2'
|
|
88
|
+
if (name === 'katex/LICENSE') return 'text/plain; charset=utf-8'
|
|
75
89
|
if (name === 'host-ui.cjs') return 'text/javascript; charset=utf-8'
|
|
76
90
|
if (name === 'host-ui.css') return 'text/css; charset=utf-8'
|
|
77
91
|
return null
|
|
@@ -104,29 +118,80 @@ async function coverIds(dir) {
|
|
|
104
118
|
}
|
|
105
119
|
}
|
|
106
120
|
|
|
121
|
+
/**
|
|
122
|
+
* The manifest summary both the JSON path-import and the upload import return,
|
|
123
|
+
* so the settings page renders one shape either way.
|
|
124
|
+
* @param {{ manifest: object }} verified - a checksum-verified backup.
|
|
125
|
+
* @returns {object} the summary.
|
|
126
|
+
*/
|
|
127
|
+
function backupSummary(verified) {
|
|
128
|
+
const included = verified.manifest.included ?? {}
|
|
129
|
+
return {
|
|
130
|
+
format: verified.manifest.format,
|
|
131
|
+
createdAt: verified.manifest.createdAt,
|
|
132
|
+
plugin: verified.manifest.plugin ?? null,
|
|
133
|
+
machine: verified.manifest.machine ?? null,
|
|
134
|
+
included,
|
|
135
|
+
paths: verified.manifest.paths ?? null,
|
|
136
|
+
files: Array.isArray(verified.manifest.files) ? verified.manifest.files.length : 0,
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* HTTP status for one import-pipeline refusal.
|
|
142
|
+
* @param {string} code - `RejectError.code`.
|
|
143
|
+
* @returns {number} status.
|
|
144
|
+
*/
|
|
145
|
+
function rejectStatus(code) {
|
|
146
|
+
if (code === 'too-large') return 413
|
|
147
|
+
if (code === 'render-unavailable') return 503
|
|
148
|
+
if (code === 'render-failed') return 502
|
|
149
|
+
if (code === 'no-library') return 409
|
|
150
|
+
return 400
|
|
151
|
+
}
|
|
152
|
+
|
|
107
153
|
/**
|
|
108
154
|
* Read the request body for a mutation.
|
|
109
155
|
* @param {import('node:http').IncomingMessage} request - inbound request.
|
|
110
156
|
* @param {import('node:http').ServerResponse} response - outbound response.
|
|
157
|
+
* @param {number} [limit] - body ceiling; defaults to the tiny position-sized cap.
|
|
111
158
|
* @returns {Promise<unknown | undefined>} the body, or undefined after a failure was answered.
|
|
112
159
|
*/
|
|
113
|
-
async function mutationBody(request, response) {
|
|
160
|
+
async function mutationBody(request, response, limit) {
|
|
114
161
|
if (!isSameOrigin(request)) {
|
|
115
162
|
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
116
163
|
return undefined
|
|
117
164
|
}
|
|
118
165
|
try {
|
|
119
|
-
return await readJson(request)
|
|
166
|
+
return limit === undefined ? await readJson(request) : await readJson(request, limit)
|
|
120
167
|
} catch (error) {
|
|
121
168
|
fail(response, 400, 'invalid-body', String(error && error.message ? error.message : error))
|
|
122
169
|
return undefined
|
|
123
170
|
}
|
|
124
171
|
}
|
|
125
172
|
|
|
173
|
+
/**
|
|
174
|
+
* The bytes behind one `data:image/...;base64,` URL.
|
|
175
|
+
* @param {string} value - the data URL the browser rasterized.
|
|
176
|
+
* @returns {{ data: Buffer, mediaType: string } | null} the bytes and media type, or null when unusable.
|
|
177
|
+
*/
|
|
178
|
+
function imageBytesOf(value) {
|
|
179
|
+
const comma = value.indexOf(',')
|
|
180
|
+
if (comma < 0) return null
|
|
181
|
+
const match = /^data:(image\/(?:png|jpeg|webp));base64$/i.exec(value.slice(0, comma))
|
|
182
|
+
if (match === null) return null
|
|
183
|
+
try {
|
|
184
|
+
const data = Buffer.from(value.slice(comma + 1), 'base64')
|
|
185
|
+
return data.length === 0 ? null : { data, mediaType: match[1].toLowerCase() }
|
|
186
|
+
} catch {
|
|
187
|
+
return null
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
126
191
|
/**
|
|
127
192
|
* Build the prefix handler for the plugin's routes.
|
|
128
193
|
* @param {{ libraryDir: string, fragmentDir: string, artifactDir: string, coverDir: string, indexPath: string, statePath: string, resumeRatio?: number, toolsDir?: string }} config - resolved paths and behavior (the profile's library is the fallback).
|
|
129
|
-
* @param {{ resolveTarget?: () => Promise<{ workspaceId: string | null, cwd: string }>, listWorkspaces?: () => Promise<Array<{ id: string, title: string, path: string }>>, pending?: { list: Function, put: Function, remove: Function }, links?: { list: Function, add: Function, remove: Function }, contextPressure?: (sessionId: string) => Promise<object | null>, libraries?: { list: Function, active: Function, add: Function, setActive: Function, remove: Function }, installToolkit?: (libraryDir: string) => Promise<object> }} [options] - host capabilities the routes expose.
|
|
194
|
+
* @param {{ resolveTarget?: () => Promise<{ workspaceId: string | null, cwd: string }>, listWorkspaces?: () => Promise<Array<{ id: string, title: string, path: string }>>, pending?: { list: Function, put: Function, remove: Function }, links?: { list: Function, add: Function, remove: Function }, contextPressure?: (sessionId: string) => Promise<object | null>, libraries?: { list: Function, active: Function, add: Function, setActive: Function, remove: Function }, translationMigration?: () => Promise<object>, revealFile?: (path: string) => void, installToolkit?: (libraryDir: string) => Promise<object>, aiTranslate?: (choice: object) => Promise<object> }} [options] - host capabilities the routes expose.
|
|
130
195
|
* @returns {(request: import('node:http').IncomingMessage, response: import('node:http').ServerResponse) => Promise<void>} the handler.
|
|
131
196
|
*/
|
|
132
197
|
export function createHandler(config, options = {}) {
|
|
@@ -152,7 +217,7 @@ export function createHandler(config, options = {}) {
|
|
|
152
217
|
* @param {string} code - chapter code.
|
|
153
218
|
* @returns {Promise<string|null>} absolute path, or null when missing.
|
|
154
219
|
*/
|
|
155
|
-
function runTool(script, args) {
|
|
220
|
+
function runTool(script, args, env = {}) {
|
|
156
221
|
const pythons = [process.env.MATH_DESK_PYTHON, 'python', 'py'].filter(Boolean)
|
|
157
222
|
return new Promise((resolve, reject) => {
|
|
158
223
|
const next = index => {
|
|
@@ -160,7 +225,7 @@ function runTool(script, args) {
|
|
|
160
225
|
reject(new Error('没有可用的 Python'))
|
|
161
226
|
return
|
|
162
227
|
}
|
|
163
|
-
execFile(pythons[index], [script, ...args], { timeout: 240000, windowsHide: true }, error => {
|
|
228
|
+
execFile(pythons[index], [script, ...args], { timeout: 240000, windowsHide: true, env: { ...process.env, ...env } }, error => {
|
|
164
229
|
if (error === null) resolve()
|
|
165
230
|
else next(index + 1)
|
|
166
231
|
})
|
|
@@ -169,13 +234,31 @@ function runTool(script, args) {
|
|
|
169
234
|
})
|
|
170
235
|
}
|
|
171
236
|
|
|
237
|
+
/**
|
|
238
|
+
* Environment for a tool that renders through the overlay kernel: the Typst
|
|
239
|
+
* location plus the overlay script name, so rebuild/realign follow the same
|
|
240
|
+
* engine the Host resolved at start-up.
|
|
241
|
+
* @param {object} options - the handler options.
|
|
242
|
+
* @returns {Record<string, string>} extra environment variables.
|
|
243
|
+
*/
|
|
244
|
+
function engineToolEnv(options) {
|
|
245
|
+
const env = {}
|
|
246
|
+
if (options !== null && options !== undefined && options.typstEnv !== null && typeof options.typstEnv === 'object') {
|
|
247
|
+
Object.assign(env, options.typstEnv)
|
|
248
|
+
}
|
|
249
|
+
if (options !== null && options !== undefined && typeof options.overlayName === 'string' && options.overlayName !== '') {
|
|
250
|
+
env.MATH_DESK_OVERLAY_SCRIPT = options.overlayName
|
|
251
|
+
}
|
|
252
|
+
return env
|
|
253
|
+
}
|
|
254
|
+
|
|
172
255
|
/**
|
|
173
256
|
* Run one bundled tool and return its stdout (PDF sizes, font sizes, blocks).
|
|
174
257
|
* @param {string} script - absolute tool path.
|
|
175
258
|
* @param {string[]} args - tool arguments.
|
|
176
259
|
* @returns {Promise<string>} the tool's stdout.
|
|
177
260
|
*/
|
|
178
|
-
function toolOutput(script, args) {
|
|
261
|
+
function toolOutput(script, args, env = {}) {
|
|
179
262
|
const pythons = [process.env.MATH_DESK_PYTHON, 'python', 'py'].filter(Boolean)
|
|
180
263
|
return new Promise((resolve, reject) => {
|
|
181
264
|
const next = index => {
|
|
@@ -186,7 +269,7 @@ function toolOutput(script, args) {
|
|
|
186
269
|
execFile(
|
|
187
270
|
pythons[index],
|
|
188
271
|
[script, ...args],
|
|
189
|
-
{ timeout: 180000, windowsHide: true, maxBuffer: 8 * 1024 * 1024 },
|
|
272
|
+
{ timeout: 180000, windowsHide: true, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, ...env } },
|
|
190
273
|
(error, stdout) => {
|
|
191
274
|
if (error === null) resolve(stdout)
|
|
192
275
|
else next(index + 1)
|
|
@@ -220,6 +303,40 @@ async function deepseekKey() {
|
|
|
220
303
|
}
|
|
221
304
|
}
|
|
222
305
|
|
|
306
|
+
/**
|
|
307
|
+
* The Host model channel one translation call uses. The client sends its stored
|
|
308
|
+
* choice; the Host resolves `follow` to the live deployment default, so the
|
|
309
|
+
* plugin never writes a model anywhere.
|
|
310
|
+
* @param {object | undefined} choice - the client's stored choice.
|
|
311
|
+
* @returns {Promise<object>} the channel (`label`, `image(bytes)`, `chat(request)`).
|
|
312
|
+
*/
|
|
313
|
+
async function aiFor(choice) {
|
|
314
|
+
if (typeof options.aiTranslate !== 'function') {
|
|
315
|
+
throw Object.assign(new Error('宿主没有可用的模型服务'), { code: 'no-llm' })
|
|
316
|
+
}
|
|
317
|
+
return await options.aiTranslate(choice)
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Answer one model-resolution failure with the code the client can act on.
|
|
322
|
+
* @param {import('node:http').ServerResponse} response - outbound response.
|
|
323
|
+
* @param {unknown} error - the thrown value.
|
|
324
|
+
* @returns {boolean} whether the failure was answered here.
|
|
325
|
+
*/
|
|
326
|
+
function answerAiFailure(response, error) {
|
|
327
|
+
const code = error !== null && error !== undefined && typeof error.code === 'string' ? error.code : ''
|
|
328
|
+
const message = String(error && error.message ? error.message : error)
|
|
329
|
+
if (code === 'model-cannot-read-image') {
|
|
330
|
+
fail(response, 422, code, message)
|
|
331
|
+
return true
|
|
332
|
+
}
|
|
333
|
+
if (code === 'no-model' || code === 'no-llm' || code === 'model-missing') {
|
|
334
|
+
fail(response, 503, code, message)
|
|
335
|
+
return true
|
|
336
|
+
}
|
|
337
|
+
return false
|
|
338
|
+
}
|
|
339
|
+
|
|
223
340
|
async function activeLibrary() {
|
|
224
341
|
if (libraries !== undefined && typeof libraries.active === 'function') {
|
|
225
342
|
return await libraries.active()
|
|
@@ -236,6 +353,46 @@ async function activeLibrary() {
|
|
|
236
353
|
}
|
|
237
354
|
}
|
|
238
355
|
|
|
356
|
+
/**
|
|
357
|
+
* The active library, or a 409 answer when the user has not added one.
|
|
358
|
+
* @param {import('node:http').ServerResponse} response - outbound response.
|
|
359
|
+
* @returns {Promise<object | null>} the library, or null after answering.
|
|
360
|
+
*/
|
|
361
|
+
async function requireLibrary(response) {
|
|
362
|
+
const library = await activeLibrary()
|
|
363
|
+
if (library === null || typeof library.libraryDir !== 'string' || library.libraryDir === '') {
|
|
364
|
+
fail(response, 409, 'no-library', '还没有书库,请先在书库页添加一个')
|
|
365
|
+
return null
|
|
366
|
+
}
|
|
367
|
+
return library
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Wait for the one-time move of the old global translation cache. Routes that
|
|
372
|
+
* read or write a chapter's cache call this first, so they never look in the
|
|
373
|
+
* new folder before the migration put the old pages there.
|
|
374
|
+
* @returns {Promise<void>}
|
|
375
|
+
*/
|
|
376
|
+
async function ensureTranslationCache() {
|
|
377
|
+
if (typeof options.translationMigration !== 'function') return
|
|
378
|
+
try {
|
|
379
|
+
await options.translationMigration()
|
|
380
|
+
} catch {
|
|
381
|
+
// The migration reports its own failures; a broken migration must not take
|
|
382
|
+
// every cache route down with it.
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Resolve a staged wizard upload token to its temp path.
|
|
388
|
+
* @param {unknown} token - `stage-<uuid>.zip`.
|
|
389
|
+
* @returns {string | null} absolute path, or null when the token is malformed.
|
|
390
|
+
*/
|
|
391
|
+
function stagedPath(token) {
|
|
392
|
+
if (typeof token !== 'string' || !/^stage-[0-9a-f-]{36}\.zip$/.test(token)) return null
|
|
393
|
+
return join(config.dataDir, 'tmp', token)
|
|
394
|
+
}
|
|
395
|
+
|
|
239
396
|
/**
|
|
240
397
|
* The bundled sample library's manifest, when the package ships one.
|
|
241
398
|
* @returns {Promise<object | null>} `{ book, files }` or null.
|
|
@@ -249,6 +406,17 @@ async function activeLibrary() {
|
|
|
249
406
|
}
|
|
250
407
|
}
|
|
251
408
|
|
|
409
|
+
/**
|
|
410
|
+
* Drop the short-lived catalog copy. Every write that adds, removes or
|
|
411
|
+
* renames books calls this, otherwise the client's immediate reload after a
|
|
412
|
+
* delete is answered from the cache and the deleted book keeps showing up.
|
|
413
|
+
* @returns {void}
|
|
414
|
+
*/
|
|
415
|
+
function invalidateCatalog() {
|
|
416
|
+
cachedCatalog = null
|
|
417
|
+
cachedAt = 0
|
|
418
|
+
}
|
|
419
|
+
|
|
252
420
|
/**
|
|
253
421
|
* The catalog of one library, reused for a couple of seconds; `fresh` rescans.
|
|
254
422
|
* @param {boolean} [fresh] - ignore the cached copy.
|
|
@@ -312,29 +480,57 @@ async function activeLibrary() {
|
|
|
312
480
|
|| path === `${PREFIX}/deepseek-key`
|
|
313
481
|
|| path.startsWith(`${PREFIX}/vendor/`)
|
|
314
482
|
|| path === `${PREFIX}/font`
|
|
483
|
+
|| path === `${PREFIX}/engine`
|
|
315
484
|
|| path === `${PREFIX}/font/file`
|
|
316
485
|
|| path === `${PREFIX}/backup/settings`
|
|
317
486
|
|| path === `${PREFIX}/state`
|
|
318
487
|
|| path === `${PREFIX}/pending`
|
|
319
488
|
|| path === `${PREFIX}/pending/remove`
|
|
320
489
|
|| path === `${PREFIX}/context`
|
|
490
|
+
|| path === `${PREFIX}/ai-catalog`
|
|
491
|
+
|| path === `${PREFIX}/ai-session`
|
|
492
|
+
|| path === `${PREFIX}/ai-probe`
|
|
493
|
+
|| path === `${PREFIX}/clear-translation-cache`
|
|
321
494
|
|| path === `${PREFIX}/purge`
|
|
495
|
+
|| path === `${PREFIX}/imports`
|
|
496
|
+
|| path === `${PREFIX}/exports`
|
|
497
|
+
|| path === `${PREFIX}/reveal`
|
|
498
|
+
|| path === `${PREFIX}/imports/stage`
|
|
499
|
+
|| path === `${PREFIX}/storage`
|
|
500
|
+
|| path === `${PREFIX}/storage/clean`
|
|
501
|
+
|| path === `${PREFIX}/exports/delete`
|
|
502
|
+
|| path === `${PREFIX}/storage/prune`
|
|
322
503
|
if (!libraryFree && (libraries === undefined || (await libraries.active()) === null)) {
|
|
323
504
|
fail(response, 409, 'no-library', '还没有书库,请先在书库页添加一个')
|
|
324
505
|
return
|
|
325
506
|
}
|
|
326
507
|
|
|
508
|
+
// The translation cache moved from the plugin data folder into the library
|
|
509
|
+
// (DEC-0014 §5). Every route that reads or writes it waits for the one-time
|
|
510
|
+
// migration first, so the new folder is never read half-migrated.
|
|
511
|
+
if (path === `${PREFIX}/blocks`
|
|
512
|
+
|| path === `${PREFIX}/translate-chapter`
|
|
513
|
+
|| path === `${PREFIX}/clear-translation-cache`
|
|
514
|
+
|| path === `${PREFIX}/rebuild-overlay`
|
|
515
|
+
|| path === `${PREFIX}/realign-overlay`
|
|
516
|
+
|| path === `${PREFIX}/rebuild-translated`) {
|
|
517
|
+
await ensureTranslationCache()
|
|
518
|
+
}
|
|
519
|
+
|
|
327
520
|
if (path === `${PREFIX}/backup`) {
|
|
328
521
|
if (request.method !== 'POST') {
|
|
329
522
|
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
330
523
|
return
|
|
331
524
|
}
|
|
332
|
-
|
|
525
|
+
// Browser settings are a portable JSON blob; the old 16 KB cap rejected a
|
|
526
|
+
// profile once it carried a few preference keys and killed the socket
|
|
527
|
+
// (the page showed net::ERR_UNEXPECTED instead of a readable error).
|
|
528
|
+
const body = await mutationBody(request, response, 16 * 1024 * 1024)
|
|
333
529
|
if (body === undefined) return
|
|
334
530
|
const record = body !== null && typeof body === 'object' ? body : {}
|
|
335
531
|
const action = typeof record.action === 'string' ? record.action : ''
|
|
336
532
|
try {
|
|
337
|
-
if (action === 'create') {
|
|
533
|
+
if (action === 'create' || action === 'create-async') {
|
|
338
534
|
const source = record.include !== null && typeof record.include === 'object' ? record.include : {}
|
|
339
535
|
const include = {
|
|
340
536
|
sessions: source.sessions !== false,
|
|
@@ -345,22 +541,36 @@ async function activeLibrary() {
|
|
|
345
541
|
fonts: source.fonts === true,
|
|
346
542
|
projcache: source.projcache === true,
|
|
347
543
|
}
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
544
|
+
const runCreate = async () => {
|
|
545
|
+
let list = []
|
|
546
|
+
if (libraries !== undefined && typeof libraries.list === 'function') {
|
|
547
|
+
const rows = await libraries.list().catch(() => [])
|
|
548
|
+
list = (Array.isArray(rows) ? rows : []).map(row => ({ id: row.id, name: row.name, libraryDir: row.libraryDir }))
|
|
549
|
+
} else {
|
|
550
|
+
const active = await activeLibrary()
|
|
551
|
+
list = [{ id: active.id, name: active.name, libraryDir: active.libraryDir }]
|
|
552
|
+
}
|
|
553
|
+
return createBackup({
|
|
554
|
+
dataDir: config.dataDir,
|
|
555
|
+
libraries: list,
|
|
556
|
+
include,
|
|
557
|
+
settings: include.settings && record.settings !== null && typeof record.settings === 'object' ? record.settings : undefined,
|
|
558
|
+
pluginVersion: PLUGIN_VERSION,
|
|
559
|
+
machine: { platform: process.platform, oldHome: process.env.USERPROFILE ?? process.env.HOME ?? '' },
|
|
560
|
+
})
|
|
561
|
+
}
|
|
562
|
+
if (action === 'create-async') {
|
|
563
|
+
// A real profile's sessions make packing take long enough that a
|
|
564
|
+
// synchronous request can be cut by the transport; return the job
|
|
565
|
+
// and let the settings page poll `GET /exports`.
|
|
566
|
+
try {
|
|
567
|
+
sendJson(response, 200, { ok: true, job: startExportJob('backup', runCreate) })
|
|
568
|
+
} catch (error) {
|
|
569
|
+
fail(response, 409, 'busy', String(error && error.message ? error.message : error))
|
|
570
|
+
}
|
|
571
|
+
return
|
|
355
572
|
}
|
|
356
|
-
const backup = await
|
|
357
|
-
dataDir: config.dataDir,
|
|
358
|
-
libraries: list,
|
|
359
|
-
include,
|
|
360
|
-
settings: include.settings && record.settings !== null && typeof record.settings === 'object' ? record.settings : undefined,
|
|
361
|
-
pluginVersion: PLUGIN_VERSION,
|
|
362
|
-
machine: { platform: process.platform, oldHome: process.env.USERPROFILE ?? process.env.HOME ?? '' },
|
|
363
|
-
})
|
|
573
|
+
const backup = await runCreate()
|
|
364
574
|
sendJson(response, 200, {
|
|
365
575
|
ok: true,
|
|
366
576
|
name: backup.name,
|
|
@@ -378,19 +588,7 @@ async function activeLibrary() {
|
|
|
378
588
|
return
|
|
379
589
|
}
|
|
380
590
|
const verified = await readBackup(source)
|
|
381
|
-
|
|
382
|
-
sendJson(response, 200, {
|
|
383
|
-
ok: true,
|
|
384
|
-
manifest: {
|
|
385
|
-
format: verified.manifest.format,
|
|
386
|
-
createdAt: verified.manifest.createdAt,
|
|
387
|
-
plugin: verified.manifest.plugin ?? null,
|
|
388
|
-
machine: verified.manifest.machine ?? null,
|
|
389
|
-
included,
|
|
390
|
-
paths: verified.manifest.paths ?? null,
|
|
391
|
-
files: Array.isArray(verified.manifest.files) ? verified.manifest.files.length : 0,
|
|
392
|
-
},
|
|
393
|
-
})
|
|
591
|
+
sendJson(response, 200, { ok: true, manifest: backupSummary(verified) })
|
|
394
592
|
return
|
|
395
593
|
}
|
|
396
594
|
if (action === 'import') {
|
|
@@ -406,6 +604,10 @@ async function activeLibrary() {
|
|
|
406
604
|
libraryRoots: Object.fromEntries(Object.entries(roots).filter(([, value]) => typeof value === 'string' && value !== '')),
|
|
407
605
|
strategy: typeof record.strategy === 'string' ? record.strategy : 'merge',
|
|
408
606
|
})
|
|
607
|
+
// An uploaded package lives in tmp/ only until its import finishes.
|
|
608
|
+
if (/^import-[0-9a-f-]+\.zip$/.test(basename(source)) && source.startsWith(join(config.dataDir, 'tmp'))) {
|
|
609
|
+
await rm(source, { force: true }).catch(() => {})
|
|
610
|
+
}
|
|
409
611
|
sendJson(response, 200, { ok: true, report })
|
|
410
612
|
return
|
|
411
613
|
}
|
|
@@ -430,7 +632,7 @@ async function activeLibrary() {
|
|
|
430
632
|
|
|
431
633
|
if (path === `${PREFIX}/backup/file`) {
|
|
432
634
|
const name = url.searchParams.get('name') ?? ''
|
|
433
|
-
if (
|
|
635
|
+
if (!isExportName(name)) {
|
|
434
636
|
fail(response, 400, 'invalid-name', '迁移包名称不合法')
|
|
435
637
|
return
|
|
436
638
|
}
|
|
@@ -443,7 +645,20 @@ async function activeLibrary() {
|
|
|
443
645
|
return
|
|
444
646
|
}
|
|
445
647
|
|
|
446
|
-
if (path === `${PREFIX}/
|
|
648
|
+
if (path === `${PREFIX}/exports`) {
|
|
649
|
+
if (request.method !== 'GET') {
|
|
650
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
|
|
651
|
+
return
|
|
652
|
+
}
|
|
653
|
+
sendJson(response, 200, {
|
|
654
|
+
ok: true,
|
|
655
|
+
items: await listExports(config.dataDir),
|
|
656
|
+
jobs: listJobs(),
|
|
657
|
+
})
|
|
658
|
+
return
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
if (path === `${PREFIX}/reveal`) {
|
|
447
662
|
if (request.method !== 'POST') {
|
|
448
663
|
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
449
664
|
return
|
|
@@ -451,32 +666,345 @@ async function activeLibrary() {
|
|
|
451
666
|
const body = await mutationBody(request, response)
|
|
452
667
|
if (body === undefined) return
|
|
453
668
|
const record = body !== null && typeof body === 'object' ? body : {}
|
|
454
|
-
const
|
|
455
|
-
if (
|
|
456
|
-
fail(response, 400, 'invalid-
|
|
669
|
+
const name = typeof record.name === 'string' ? record.name : ''
|
|
670
|
+
if (!isExportName(name)) {
|
|
671
|
+
fail(response, 400, 'invalid-name', '不是插件的打包文件')
|
|
457
672
|
return
|
|
458
673
|
}
|
|
459
|
-
const
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
fail(response, 400, 'invalid-subdir', '子目录不能包含 ..')
|
|
674
|
+
const file = join(config.dataDir, 'backup', name)
|
|
675
|
+
const info = await stat(file).catch(() => null)
|
|
676
|
+
if (info === null || !info.isFile()) {
|
|
677
|
+
fail(response, 404, 'missing-file', '找不到这个文件')
|
|
464
678
|
return
|
|
465
679
|
}
|
|
466
680
|
try {
|
|
467
|
-
const
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
681
|
+
const reveal = typeof options.revealFile === 'function' ? options.revealFile : revealInFileManager
|
|
682
|
+
reveal(file)
|
|
683
|
+
sendJson(response, 200, { ok: true })
|
|
684
|
+
} catch (error) {
|
|
685
|
+
fail(response, 500, 'reveal-failed', String(error && error.message ? error.message : error))
|
|
686
|
+
}
|
|
687
|
+
return
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// Settings → 数据 shows where the space went. Reading is always safe and
|
|
691
|
+
// costs nothing at startup: the panel asks when it opens (DEC-0014 §4).
|
|
692
|
+
if (path === `${PREFIX}/storage`) {
|
|
693
|
+
if (request.method !== 'GET') {
|
|
694
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
|
|
695
|
+
return
|
|
696
|
+
}
|
|
697
|
+
try {
|
|
698
|
+
const listed = libraries === undefined ? { items: [] } : await libraries.list().catch(() => ({ items: [] }))
|
|
699
|
+
const report = await measureStorage({
|
|
700
|
+
dataDir: config.dataDir,
|
|
701
|
+
libraries: Array.isArray(listed.items) ? listed.items : [],
|
|
702
|
+
})
|
|
703
|
+
sendJson(response, 200, { ok: true, ...report })
|
|
704
|
+
} catch (error) {
|
|
705
|
+
fail(response, 500, 'storage-failed', String(error && error.message ? error.message : error))
|
|
706
|
+
}
|
|
707
|
+
return
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// Only what an interrupted run left behind: upload scratch, stale stage
|
|
711
|
+
// packages and a half-packed staging tree. A running packing job owns its
|
|
712
|
+
// staging tree, so nothing under `backup/` is touched while one runs.
|
|
713
|
+
if (path === `${PREFIX}/storage/clean`) {
|
|
714
|
+
if (request.method !== 'POST') {
|
|
715
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
716
|
+
return
|
|
717
|
+
}
|
|
718
|
+
if (!isSameOrigin(request)) {
|
|
719
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
720
|
+
return
|
|
721
|
+
}
|
|
722
|
+
try {
|
|
723
|
+
const busy = listJobs().some(job => job.status === 'running')
|
|
724
|
+
const result = await cleanTemporary({ dataDir: config.dataDir, busy })
|
|
725
|
+
sendJson(response, 200, { ok: true, ...result })
|
|
726
|
+
} catch (error) {
|
|
727
|
+
fail(response, 500, 'storage-clean-failed', String(error && error.message ? error.message : error))
|
|
728
|
+
}
|
|
729
|
+
return
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// The user asked for a way off the packing history: a package is only a
|
|
733
|
+
// file in `backup/`, so deleting removes exactly that one file and the
|
|
734
|
+
// record disappears with it (the history is a directory scan).
|
|
735
|
+
if (path === `${PREFIX}/exports/delete`) {
|
|
736
|
+
if (request.method !== 'POST') {
|
|
737
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
738
|
+
return
|
|
739
|
+
}
|
|
740
|
+
if (!isSameOrigin(request)) {
|
|
741
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
742
|
+
return
|
|
743
|
+
}
|
|
744
|
+
const body = await mutationBody(request, response)
|
|
745
|
+
if (body === undefined) return
|
|
746
|
+
const record = body !== null && typeof body === 'object' ? body : {}
|
|
747
|
+
const name = typeof record.name === 'string' ? record.name : ''
|
|
748
|
+
if (!isExportName(name)) {
|
|
749
|
+
fail(response, 400, 'invalid-name', '不是插件的打包文件')
|
|
750
|
+
return
|
|
751
|
+
}
|
|
752
|
+
const file = join(config.dataDir, 'backup', name)
|
|
753
|
+
const info = await stat(file).catch(() => null)
|
|
754
|
+
if (info === null || !info.isFile()) {
|
|
755
|
+
fail(response, 404, 'missing-file', '找不到这个打包文件')
|
|
756
|
+
return
|
|
757
|
+
}
|
|
758
|
+
try {
|
|
759
|
+
await rm(file, { force: true })
|
|
760
|
+
sendJson(response, 200, { ok: true })
|
|
761
|
+
} catch (error) {
|
|
762
|
+
fail(response, 500, 'export-delete-failed', String(error && error.message ? error.message : error))
|
|
763
|
+
}
|
|
764
|
+
return
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// Opens one library's folder in the OS file manager. The card already
|
|
768
|
+
// shows the path; this saves the user from copying it into Explorer.
|
|
769
|
+
if (path === `${PREFIX}/library/reveal`) {
|
|
770
|
+
if (request.method !== 'POST') {
|
|
771
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
772
|
+
return
|
|
773
|
+
}
|
|
774
|
+
if (!isSameOrigin(request)) {
|
|
775
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
776
|
+
return
|
|
777
|
+
}
|
|
778
|
+
const body = await mutationBody(request, response)
|
|
779
|
+
if (body === undefined) return
|
|
780
|
+
const record = body !== null && typeof body === 'object' ? body : {}
|
|
781
|
+
const wanted = typeof record.library === 'string' ? record.library : ''
|
|
782
|
+
const library = await requireLibrary(response)
|
|
783
|
+
if (library === null) return
|
|
784
|
+
let target = library
|
|
785
|
+
if (wanted !== '' && libraries !== undefined) {
|
|
786
|
+
const listed = await libraries.list().catch(() => ({ items: [] }))
|
|
787
|
+
const found = (Array.isArray(listed.items) ? listed.items : [])
|
|
788
|
+
.find(item => item !== null && typeof item === 'object' && item.id === wanted)
|
|
789
|
+
if (found !== undefined && typeof found.libraryDir === 'string' && found.libraryDir !== '') target = found
|
|
790
|
+
}
|
|
791
|
+
try {
|
|
792
|
+
const reveal = typeof options.revealDirectory === 'function' ? options.revealDirectory : revealDirectory
|
|
793
|
+
reveal(target.libraryDir)
|
|
794
|
+
sendJson(response, 200, { ok: true, path: target.libraryDir })
|
|
795
|
+
} catch (error) {
|
|
796
|
+
fail(response, 500, 'reveal-failed', String(error && error.message ? error.message : error))
|
|
797
|
+
}
|
|
798
|
+
return
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// Retention is a button, not a timer: the three windows below only ever run
|
|
802
|
+
// because the user pressed one, and each one is explicit about its target.
|
|
803
|
+
if (path === `${PREFIX}/storage/prune`) {
|
|
804
|
+
if (request.method !== 'POST') {
|
|
805
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
806
|
+
return
|
|
807
|
+
}
|
|
808
|
+
if (!isSameOrigin(request)) {
|
|
809
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
810
|
+
return
|
|
811
|
+
}
|
|
812
|
+
const body = await mutationBody(request, response)
|
|
813
|
+
if (body === undefined) return
|
|
814
|
+
const record = body !== null && typeof body === 'object' ? body : {}
|
|
815
|
+
const target = record.target === 'trash' || record.target === 'translation' || record.target === 'jobs' ? record.target : ''
|
|
816
|
+
const days = Math.max(1, Math.min(3650, Math.round(Number(record.days) || 90)))
|
|
817
|
+
if (target === '') {
|
|
818
|
+
fail(response, 400, 'bad-target', '未知的清理目标')
|
|
819
|
+
return
|
|
820
|
+
}
|
|
821
|
+
try {
|
|
822
|
+
let result = { removed: 0, bytes: 0 }
|
|
823
|
+
if (target === 'jobs') {
|
|
824
|
+
result = await pruneStaleJobs({ dataDir: config.dataDir, days })
|
|
825
|
+
} else if (target === 'translation') {
|
|
826
|
+
const listed = libraries === undefined ? { items: [] } : await libraries.list().catch(() => ({ items: [] }))
|
|
827
|
+
result = await pruneTranslationIdle({
|
|
828
|
+
libraries: Array.isArray(listed.items) ? listed.items : [],
|
|
829
|
+
days,
|
|
830
|
+
})
|
|
831
|
+
} else {
|
|
832
|
+
const library = await requireLibrary(response)
|
|
833
|
+
if (library === null) return
|
|
834
|
+
result = await pruneTrash({ library, days })
|
|
835
|
+
}
|
|
836
|
+
sendJson(response, 200, { ok: true, target, days, ...result })
|
|
837
|
+
} catch (error) {
|
|
838
|
+
fail(response, 500, 'storage-prune-failed', String(error && error.message ? error.message : error))
|
|
839
|
+
}
|
|
840
|
+
return
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
// Content-duplicate report. Read-only by design: the PDFs belong to the
|
|
844
|
+
// user, so the panel only tells them which files are the same.
|
|
845
|
+
if (path === `${PREFIX}/duplicates`) {
|
|
846
|
+
if (request.method !== 'GET') {
|
|
847
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
|
|
848
|
+
return
|
|
849
|
+
}
|
|
850
|
+
const library = await requireLibrary(response)
|
|
851
|
+
if (library === null) return
|
|
852
|
+
try {
|
|
853
|
+
sendJson(response, 200, { ok: true, ...(await scanDuplicates({ library })) })
|
|
854
|
+
} catch (error) {
|
|
855
|
+
fail(response, 500, 'duplicates-failed', String(error && error.message ? error.message : error))
|
|
856
|
+
}
|
|
857
|
+
return
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
if (path === `${PREFIX}/library-export`) {
|
|
861
|
+
if (request.method !== 'POST') {
|
|
862
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
863
|
+
return
|
|
864
|
+
}
|
|
865
|
+
const body = await mutationBody(request, response)
|
|
866
|
+
if (body === undefined) return
|
|
867
|
+
const record = body !== null && typeof body === 'object' ? body : {}
|
|
868
|
+
const library = await requireLibrary(response)
|
|
869
|
+
if (library === null) return
|
|
870
|
+
const runExport = () => exportLibrary({
|
|
871
|
+
library,
|
|
872
|
+
dataDir: config.dataDir,
|
|
873
|
+
includeArtifacts: record.includeArtifacts === true,
|
|
874
|
+
})
|
|
875
|
+
if (record.async === true) {
|
|
876
|
+
try {
|
|
877
|
+
sendJson(response, 200, { ok: true, job: startExportJob('library-export', runExport) })
|
|
878
|
+
} catch (error) {
|
|
879
|
+
fail(response, 409, 'busy', String(error && error.message ? error.message : error))
|
|
880
|
+
}
|
|
881
|
+
return
|
|
882
|
+
}
|
|
883
|
+
try {
|
|
884
|
+
const result = await runExport()
|
|
885
|
+
sendJson(response, 200, {
|
|
886
|
+
ok: true,
|
|
887
|
+
...result,
|
|
888
|
+
download: `${PREFIX}/backup/file?name=${encodeURIComponent(result.name)}`,
|
|
476
889
|
})
|
|
477
|
-
sendJson(response, 200, { ok: true, report })
|
|
478
890
|
} catch (error) {
|
|
479
|
-
fail(response, 500, 'library-
|
|
891
|
+
fail(response, 500, 'library-export-failed', String(error && error.message ? error.message : error))
|
|
892
|
+
}
|
|
893
|
+
return
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
if (path === `${PREFIX}/pdf-export`) {
|
|
897
|
+
if (request.method !== 'POST') {
|
|
898
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
899
|
+
return
|
|
900
|
+
}
|
|
901
|
+
const body = await mutationBody(request, response)
|
|
902
|
+
if (body === undefined) return
|
|
903
|
+
const record = body !== null && typeof body === 'object' ? body : {}
|
|
904
|
+
const library = await requireLibrary(response)
|
|
905
|
+
if (library === null) return
|
|
906
|
+
const runExport = () => exportPdfPack({
|
|
907
|
+
library,
|
|
908
|
+
dataDir: config.dataDir,
|
|
909
|
+
scope: record.scope === 'fragments' || record.scope === 'whole' ? record.scope : 'both',
|
|
910
|
+
})
|
|
911
|
+
if (record.async === true) {
|
|
912
|
+
try {
|
|
913
|
+
sendJson(response, 200, { ok: true, job: startExportJob('pdf-pack', runExport) })
|
|
914
|
+
} catch (error) {
|
|
915
|
+
fail(response, 409, 'busy', String(error && error.message ? error.message : error))
|
|
916
|
+
}
|
|
917
|
+
return
|
|
918
|
+
}
|
|
919
|
+
try {
|
|
920
|
+
const result = await runExport()
|
|
921
|
+
sendJson(response, 200, { ok: true, ...result, download: `${PREFIX}/backup/file?name=${encodeURIComponent(result.name)}` })
|
|
922
|
+
} catch (error) {
|
|
923
|
+
fail(response, 500, 'pdf-export-failed', String(error && error.message ? error.message : error))
|
|
924
|
+
}
|
|
925
|
+
return
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
if (path === `${PREFIX}/engine`) {
|
|
929
|
+
const typeset = options.typeset ?? {}
|
|
930
|
+
if (request.method === 'GET') {
|
|
931
|
+
sendJson(response, 200, {
|
|
932
|
+
ok: true,
|
|
933
|
+
engine: typeof typeset.engine === 'string' ? typeset.engine : 'latex',
|
|
934
|
+
typst: typeof typeset.typst === 'string' ? typeset.typst : '',
|
|
935
|
+
version: typeof typeset.version === 'string' ? typeset.version : '',
|
|
936
|
+
source: typeof typeset.source === 'string' ? typeset.source : 'missing',
|
|
937
|
+
installed: installed(),
|
|
938
|
+
pinnedVersion: TYPST_VERSION,
|
|
939
|
+
platform: process.platform,
|
|
940
|
+
})
|
|
941
|
+
return
|
|
942
|
+
}
|
|
943
|
+
if (request.method !== 'POST') {
|
|
944
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 GET 或 POST')
|
|
945
|
+
return
|
|
946
|
+
}
|
|
947
|
+
if (!isSameOrigin(request)) {
|
|
948
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
949
|
+
return
|
|
950
|
+
}
|
|
951
|
+
try {
|
|
952
|
+
sendJson(response, 200, { ok: true, ...(await installTypst()) })
|
|
953
|
+
} catch (error) {
|
|
954
|
+
const code = error !== null && error !== undefined && error.code ? String(error.code) : 'install-failed'
|
|
955
|
+
fail(response, code === 'unsupported' ? 400 : 502, code, String(error && error.message ? error.message : error))
|
|
956
|
+
}
|
|
957
|
+
return
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
if (path === `${PREFIX}/split`) {
|
|
961
|
+
if (request.method !== 'POST') {
|
|
962
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
963
|
+
return
|
|
964
|
+
}
|
|
965
|
+
if (!isSameOrigin(request)) {
|
|
966
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
967
|
+
return
|
|
968
|
+
}
|
|
969
|
+
let body
|
|
970
|
+
try {
|
|
971
|
+
body = await readJson(request, 1024 * 1024)
|
|
972
|
+
} catch (error) {
|
|
973
|
+
fail(response, 400, 'invalid-body', String(error && error.message ? error.message : error))
|
|
974
|
+
return
|
|
975
|
+
}
|
|
976
|
+
const book = typeof body.book === 'string' ? body.book : ''
|
|
977
|
+
const ranges = typeof body.ranges === 'string' ? body.ranges : ''
|
|
978
|
+
if (book === '' || ranges === '') {
|
|
979
|
+
fail(response, 400, 'invalid-body', '缺少 book 或 ranges')
|
|
980
|
+
return
|
|
981
|
+
}
|
|
982
|
+
const current = await loadCatalog(config)
|
|
983
|
+
const row = Array.isArray(current.books) ? current.books.find(item => item.id === book) : undefined
|
|
984
|
+
if (row === undefined) {
|
|
985
|
+
fail(response, 404, 'unknown-book', '没有这本书')
|
|
986
|
+
return
|
|
987
|
+
}
|
|
988
|
+
const chapters = Array.isArray(row.chapters) ? row.chapters : []
|
|
989
|
+
const chapter = chapters.find(item => item.whole === true) ?? chapters[0]
|
|
990
|
+
if (chapter === undefined) {
|
|
991
|
+
fail(response, 404, 'unknown-chapter', '这本书没有可拆分的 PDF')
|
|
992
|
+
return
|
|
993
|
+
}
|
|
994
|
+
const library = await activeLibrary()
|
|
995
|
+
const source = chapterPdfPath(library, row, chapter)
|
|
996
|
+
if (source.ok !== true || typeof source.path !== 'string') {
|
|
997
|
+
fail(response, 404, 'not-found', '找不到整本 PDF')
|
|
998
|
+
return
|
|
999
|
+
}
|
|
1000
|
+
// 输出按书库规则写进 `分片/<书id>/`,命名交给 split_pdf.py(与书库同一套规则)。
|
|
1001
|
+
const outDir = join(library.fragmentDir, book)
|
|
1002
|
+
try {
|
|
1003
|
+
const output = await runTool('split_pdf.py', [source.path, outDir, '--id', book, '--ranges', ranges])
|
|
1004
|
+
invalidateCatalog()
|
|
1005
|
+
sendJson(response, 200, { ok: true, outDir, output })
|
|
1006
|
+
} catch (error) {
|
|
1007
|
+
fail(response, 502, 'split-failed', String(error && error.message ? error.message : error))
|
|
480
1008
|
}
|
|
481
1009
|
return
|
|
482
1010
|
}
|
|
@@ -584,6 +1112,8 @@ async function activeLibrary() {
|
|
|
584
1112
|
indexPath: '',
|
|
585
1113
|
covers: [],
|
|
586
1114
|
target: { workspaceId: null, cwd: '' },
|
|
1115
|
+
// Read-only display value: the settings page shows it and never writes it.
|
|
1116
|
+
dataDir: config.dataDir,
|
|
587
1117
|
environment: { ...detectEnvironment(), apiKey: (await deepseekKey()) !== '' },
|
|
588
1118
|
workspaces: typeof options.listWorkspaces === 'function' ? await options.listWorkspaces() : [],
|
|
589
1119
|
resumeRatio: typeof config.resumeRatio === 'number' ? config.resumeRatio : 0.85,
|
|
@@ -648,6 +1178,8 @@ async function activeLibrary() {
|
|
|
648
1178
|
indexPath: library.indexPath,
|
|
649
1179
|
covers: await coverIds(library.coverDir),
|
|
650
1180
|
target,
|
|
1181
|
+
// Read-only display value: the settings page shows it and never writes it.
|
|
1182
|
+
dataDir: config.dataDir,
|
|
651
1183
|
environment: { ...detectEnvironment(), apiKey: (await deepseekKey()) !== '' },
|
|
652
1184
|
workspaces: typeof options.listWorkspaces === 'function' ? await options.listWorkspaces() : [],
|
|
653
1185
|
resumeRatio: typeof config.resumeRatio === 'number' ? config.resumeRatio : 0.85,
|
|
@@ -700,7 +1232,7 @@ async function activeLibrary() {
|
|
|
700
1232
|
return
|
|
701
1233
|
}
|
|
702
1234
|
const out = `${source.slice(0, source.length - 3)}.pdf`
|
|
703
|
-
await renderMarkdown(options.md2texScript, source, out)
|
|
1235
|
+
await renderMarkdown(options.md2texScript, source, out, engineToolEnv(options))
|
|
704
1236
|
sendJson(response, 200, { ok: true, path: out })
|
|
705
1237
|
} catch (error) {
|
|
706
1238
|
fail(response, 503, 'render-failed', String(error && error.message ? error.message : error))
|
|
@@ -783,7 +1315,43 @@ async function activeLibrary() {
|
|
|
783
1315
|
source,
|
|
784
1316
|
pageIndex: page,
|
|
785
1317
|
})
|
|
786
|
-
|
|
1318
|
+
// The overlay records where each translated block actually landed; the
|
|
1319
|
+
// reader's "框选整页" boxes are cut from that record when it exists, so
|
|
1320
|
+
// a frame never has to guess the translation's size. Older translations
|
|
1321
|
+
// have no layout and keep the original-box fallback.
|
|
1322
|
+
let pageSize = null
|
|
1323
|
+
try {
|
|
1324
|
+
const layout = JSON.parse(await readFile(
|
|
1325
|
+
join(chapterCacheDir(library, book, code), `page-${String(page).padStart(3, '0')}.layout.json`),
|
|
1326
|
+
'utf8'))
|
|
1327
|
+
const rows = layout !== null && typeof layout === 'object' && Array.isArray(layout.blocks) ? layout.blocks : []
|
|
1328
|
+
if (layout !== null && typeof layout === 'object' && layout.page !== null && typeof layout.page === 'object'
|
|
1329
|
+
&& Number.isFinite(Number(layout.page.width)) && Number.isFinite(Number(layout.page.height))) {
|
|
1330
|
+
pageSize = { width: Number(layout.page.width), height: Number(layout.page.height) }
|
|
1331
|
+
}
|
|
1332
|
+
const byId = new Map(rows.map(row => [String(row.id), row]))
|
|
1333
|
+
for (const block of blocks) {
|
|
1334
|
+
const row = byId.get(String(block.id))
|
|
1335
|
+
if (row === undefined || !Array.isArray(row.dst) || row.dst.length !== 4) continue
|
|
1336
|
+
const dst = row.dst.map(Number)
|
|
1337
|
+
if (!dst.every(Number.isFinite)) continue
|
|
1338
|
+
block.dst = dst
|
|
1339
|
+
if (Number.isFinite(Number(row.fontPt))) block.fontPt = Number(row.fontPt)
|
|
1340
|
+
// What a DOM text layer needs to put the same text on the same
|
|
1341
|
+
// printed baseline; absent in sidecars written before v1.5.
|
|
1342
|
+
if (Array.isArray(row.box) && row.box.length === 4) {
|
|
1343
|
+
const box = row.box.map(Number)
|
|
1344
|
+
if (box.every(Number.isFinite)) block.box = box
|
|
1345
|
+
}
|
|
1346
|
+
if (Number.isFinite(Number(row.baseline))) block.baseline = Number(row.baseline)
|
|
1347
|
+
if (Number.isFinite(Number(row.leadingPt))) block.leadingPt = Number(row.leadingPt)
|
|
1348
|
+
if (typeof row.align === 'string') block.align = row.align
|
|
1349
|
+
if (typeof row.overflow === 'boolean') block.overflow = row.overflow
|
|
1350
|
+
}
|
|
1351
|
+
} catch {
|
|
1352
|
+
// No layout for this page yet.
|
|
1353
|
+
}
|
|
1354
|
+
sendJson(response, 200, { ok: true, blocks, page: pageSize })
|
|
787
1355
|
} catch (error) {
|
|
788
1356
|
fail(response, 500, 'blocks-failed', String(error && error.message ? error.message : error))
|
|
789
1357
|
}
|
|
@@ -912,6 +1480,57 @@ async function activeLibrary() {
|
|
|
912
1480
|
return
|
|
913
1481
|
}
|
|
914
1482
|
|
|
1483
|
+
// The per-page Markdown/block caches only matter while a chapter is being
|
|
1484
|
+
// translated or resumed; once the PDF is produced they are dead weight.
|
|
1485
|
+
// Settings → 数据 offers one button instead of asking the user to find the
|
|
1486
|
+
// folder. Running jobs own their state file and are left alone.
|
|
1487
|
+
if (path === `${PREFIX}/clear-translation-cache`) {
|
|
1488
|
+
if (request.method !== 'POST') {
|
|
1489
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
1490
|
+
return
|
|
1491
|
+
}
|
|
1492
|
+
try {
|
|
1493
|
+
let removed = 0
|
|
1494
|
+
let skipped = 0
|
|
1495
|
+
// Every registered library owns its own cache now; the legacy global
|
|
1496
|
+
// folder is still cleared so a pre-migration leftover cannot linger.
|
|
1497
|
+
const roots = []
|
|
1498
|
+
const listed = libraries === undefined ? { items: [] } : await libraries.list()
|
|
1499
|
+
for (const item of Array.isArray(listed.items) ? listed.items : []) {
|
|
1500
|
+
if (item !== null && typeof item === 'object' && typeof item.libraryDir === 'string' && item.libraryDir !== '') {
|
|
1501
|
+
roots.push(translationRoot(item))
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
roots.push(legacyTranslationRoot(config.dataDir))
|
|
1505
|
+
roots.push(join(config.dataDir, 'translate-jobs'))
|
|
1506
|
+
for (const root of roots) {
|
|
1507
|
+
const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
|
|
1508
|
+
for (const entry of entries) {
|
|
1509
|
+
const target = join(root, entry.name)
|
|
1510
|
+
if (entry.isFile() && entry.name.endsWith('.json')) {
|
|
1511
|
+
let running = false
|
|
1512
|
+
try {
|
|
1513
|
+
const state = JSON.parse(await readFile(target, 'utf8'))
|
|
1514
|
+
running = state !== null && typeof state === 'object' && state.status === 'running'
|
|
1515
|
+
} catch {
|
|
1516
|
+
running = false
|
|
1517
|
+
}
|
|
1518
|
+
if (running) {
|
|
1519
|
+
skipped += 1
|
|
1520
|
+
continue
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
await rm(target, { recursive: true, force: true })
|
|
1524
|
+
removed += 1
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
sendJson(response, 200, { ok: true, removed, skipped })
|
|
1528
|
+
} catch (error) {
|
|
1529
|
+
fail(response, 500, 'clear-cache-failed', String(error && error.message ? error.message : error))
|
|
1530
|
+
}
|
|
1531
|
+
return
|
|
1532
|
+
}
|
|
1533
|
+
|
|
915
1534
|
if (path === `${PREFIX}/translate-chapter`) {
|
|
916
1535
|
if (request.method !== 'POST') {
|
|
917
1536
|
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
@@ -930,14 +1549,26 @@ async function activeLibrary() {
|
|
|
930
1549
|
return
|
|
931
1550
|
}
|
|
932
1551
|
const outPath = join(dirname(source), `${basename(source, '.pdf')}_translated.pdf`)
|
|
1552
|
+
// Resolve the model before the job starts: a model that cannot read
|
|
1553
|
+
// images (or a missing one) is a 4xx the user can act on, not a job
|
|
1554
|
+
// that runs to the end with zero translated pages.
|
|
1555
|
+
let ai
|
|
1556
|
+
try {
|
|
1557
|
+
ai = await aiFor(body.ai)
|
|
1558
|
+
} catch (error) {
|
|
1559
|
+
if (answerAiFailure(response, error)) return
|
|
1560
|
+
throw error
|
|
1561
|
+
}
|
|
933
1562
|
const jobId = await startChapterJob({
|
|
934
1563
|
jobDir: join(config.dataDir, 'translate-jobs'),
|
|
935
|
-
cacheDir:
|
|
1564
|
+
cacheDir: chapterCacheDir(library, body.book, body.code),
|
|
936
1565
|
toolsDir: config.toolsDir,
|
|
937
1566
|
overlayPath: join(dirname(source), `${basename(source, '.pdf')}_overlay.pdf`),
|
|
938
1567
|
rasterScript: join(config.toolsDir, 'pdf_raster.py'),
|
|
939
1568
|
md2texScript: options.md2texScript,
|
|
940
|
-
|
|
1569
|
+
overlayScript: options.overlayScript,
|
|
1570
|
+
typstEnv: options.typstEnv,
|
|
1571
|
+
ai,
|
|
941
1572
|
source,
|
|
942
1573
|
outPath,
|
|
943
1574
|
target,
|
|
@@ -1404,9 +2035,10 @@ async function activeLibrary() {
|
|
|
1404
2035
|
fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
|
|
1405
2036
|
return
|
|
1406
2037
|
}
|
|
1407
|
-
const cacheDir =
|
|
2038
|
+
const cacheDir = chapterCacheDir(library, body.book, body.code)
|
|
1408
2039
|
const outPath = join(dirname(source), `${basename(source, '.pdf')}_overlay.pdf`)
|
|
1409
|
-
await runTool(join(config.toolsDir, 'rebuild_overlay.py'), [source, cacheDir, outPath, config.toolsDir]
|
|
2040
|
+
await runTool(join(config.toolsDir, 'rebuild_overlay.py'), [source, cacheDir, outPath, config.toolsDir],
|
|
2041
|
+
engineToolEnv(options))
|
|
1410
2042
|
sendJson(response, 200, { ok: true, pdf: basename(outPath) })
|
|
1411
2043
|
} catch (error) {
|
|
1412
2044
|
fail(response, 500, 'rebuild-overlay-failed', String(error && error.message ? error.message : error))
|
|
@@ -1427,7 +2059,7 @@ async function activeLibrary() {
|
|
|
1427
2059
|
fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
|
|
1428
2060
|
return
|
|
1429
2061
|
}
|
|
1430
|
-
const cacheDir =
|
|
2062
|
+
const cacheDir = chapterCacheDir(library, body.book, body.code)
|
|
1431
2063
|
let pages = []
|
|
1432
2064
|
try {
|
|
1433
2065
|
pages = (await readdir(cacheDir)).filter(name => /^page-\d+\.md$/.test(name))
|
|
@@ -1442,7 +2074,8 @@ async function activeLibrary() {
|
|
|
1442
2074
|
// This is an approximation built from cached text, so the overlay it
|
|
1443
2075
|
// replaces stays next to it as `.bak` instead of just vanishing.
|
|
1444
2076
|
await copyFile(outPath, `${outPath}.bak`).catch(() => {})
|
|
1445
|
-
await runTool(join(config.toolsDir, 'realign_overlay.py'), [source, cacheDir, outPath, config.toolsDir]
|
|
2077
|
+
await runTool(join(config.toolsDir, 'realign_overlay.py'), [source, cacheDir, outPath, config.toolsDir],
|
|
2078
|
+
engineToolEnv(options))
|
|
1446
2079
|
sendJson(response, 200, { ok: true, pdf: basename(outPath) })
|
|
1447
2080
|
} catch (error) {
|
|
1448
2081
|
fail(response, 500, 'realign-overlay-failed', String(error && error.message ? error.message : error))
|
|
@@ -1463,7 +2096,7 @@ async function activeLibrary() {
|
|
|
1463
2096
|
fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
|
|
1464
2097
|
return
|
|
1465
2098
|
}
|
|
1466
|
-
const cacheDir =
|
|
2099
|
+
const cacheDir = chapterCacheDir(library, body.book, body.code)
|
|
1467
2100
|
let pages = []
|
|
1468
2101
|
try {
|
|
1469
2102
|
pages = (await readdir(cacheDir)).filter(name => /^page-\d+\.md$/.test(name)).sort()
|
|
@@ -1475,8 +2108,9 @@ async function activeLibrary() {
|
|
|
1475
2108
|
return
|
|
1476
2109
|
}
|
|
1477
2110
|
const outPath = join(dirname(source), `${basename(source, '.pdf')}_translated.pdf`)
|
|
1478
|
-
// Re-render only when the renderer changed: the marker
|
|
1479
|
-
// bilingual mode from spending seconds in
|
|
2111
|
+
// Re-render only when the renderer (or its engine) changed: the marker
|
|
2112
|
+
// keeps re-opening bilingual mode from spending seconds in a compiler.
|
|
2113
|
+
const renderTag = `${PLUGIN_VERSION}-${typeof options.overlayName === 'string' && options.overlayName.includes('typst') ? 'typst' : 'latex'}`
|
|
1480
2114
|
const marker = join(cacheDir, '.render-version')
|
|
1481
2115
|
let rendered = ''
|
|
1482
2116
|
try {
|
|
@@ -1484,7 +2118,7 @@ async function activeLibrary() {
|
|
|
1484
2118
|
} catch {
|
|
1485
2119
|
rendered = ''
|
|
1486
2120
|
}
|
|
1487
|
-
if (rendered ===
|
|
2121
|
+
if (rendered === renderTag) {
|
|
1488
2122
|
sendJson(response, 200, { ok: true, skipped: true, pdf: basename(outPath) })
|
|
1489
2123
|
return
|
|
1490
2124
|
}
|
|
@@ -1500,7 +2134,7 @@ async function activeLibrary() {
|
|
|
1500
2134
|
} catch {
|
|
1501
2135
|
paper = ''
|
|
1502
2136
|
}
|
|
1503
|
-
const draft = join(cacheDir, `.render-${
|
|
2137
|
+
const draft = join(cacheDir, `.render-${renderTag}.md`)
|
|
1504
2138
|
await writeFile(draft, chunks.join('\n\n\\newpage\n\n'), 'utf8')
|
|
1505
2139
|
try {
|
|
1506
2140
|
await renderMarkdown(
|
|
@@ -1508,6 +2142,7 @@ async function activeLibrary() {
|
|
|
1508
2142
|
draft,
|
|
1509
2143
|
outPath,
|
|
1510
2144
|
{
|
|
2145
|
+
...engineToolEnv(options),
|
|
1511
2146
|
// No generated heading: the pages carry the book's own one.
|
|
1512
2147
|
MATH_DESK_NO_TITLE: '1',
|
|
1513
2148
|
...(paper === '' ? {} : { MATH_DESK_PAPER: paper }),
|
|
@@ -1516,7 +2151,7 @@ async function activeLibrary() {
|
|
|
1516
2151
|
} finally {
|
|
1517
2152
|
await unlink(draft).catch(() => {})
|
|
1518
2153
|
}
|
|
1519
|
-
await writeFile(marker,
|
|
2154
|
+
await writeFile(marker, renderTag, 'utf8').catch(() => {})
|
|
1520
2155
|
sendJson(response, 200, { ok: true, pdf: basename(outPath) })
|
|
1521
2156
|
} catch (error) {
|
|
1522
2157
|
fail(response, 500, 'rebuild-translated-failed', String(error && error.message ? error.message : error))
|
|
@@ -1540,6 +2175,11 @@ async function activeLibrary() {
|
|
|
1540
2175
|
fail(response, 413, 'image-too-large', '页面图片过大,请降低渲染倍率')
|
|
1541
2176
|
return
|
|
1542
2177
|
}
|
|
2178
|
+
const decoded = imageBytesOf(image)
|
|
2179
|
+
if (decoded === null) {
|
|
2180
|
+
fail(response, 400, 'bad-image', '页面图片格式不支持(需要 PNG/JPEG/WebP)')
|
|
2181
|
+
return
|
|
2182
|
+
}
|
|
1543
2183
|
const target = body.target === 'zh' ? 'zh' : 'en'
|
|
1544
2184
|
const library = await activeLibrary()
|
|
1545
2185
|
const source = await chapterPdf(library, body.book, body.code)
|
|
@@ -1549,7 +2189,15 @@ async function activeLibrary() {
|
|
|
1549
2189
|
}
|
|
1550
2190
|
const dir = dirname(source)
|
|
1551
2191
|
const name = basename(source)
|
|
1552
|
-
|
|
2192
|
+
let ai
|
|
2193
|
+
try {
|
|
2194
|
+
ai = await aiFor(body.ai)
|
|
2195
|
+
} catch (error) {
|
|
2196
|
+
if (answerAiFailure(response, error)) return
|
|
2197
|
+
throw error
|
|
2198
|
+
}
|
|
2199
|
+
const imageRef = await ai.image(decoded.data, decoded.mediaType)
|
|
2200
|
+
const markdown = await translatePage({ chat: ai.chat, image: imageRef, target })
|
|
1553
2201
|
if (body.mdOnly === true) {
|
|
1554
2202
|
sendJson(response, 200, { ok: true, md: markdown })
|
|
1555
2203
|
return
|
|
@@ -1560,7 +2208,7 @@ async function activeLibrary() {
|
|
|
1560
2208
|
try {
|
|
1561
2209
|
// The translated page keeps the book's own chapter heading; a
|
|
1562
2210
|
// generated one would print the temp file name above it.
|
|
1563
|
-
await renderMarkdown(options.md2texScript, mdPath, out, { MATH_DESK_NO_TITLE: '1' })
|
|
2211
|
+
await renderMarkdown(options.md2texScript, mdPath, out, { ...engineToolEnv(options), MATH_DESK_NO_TITLE: '1' })
|
|
1564
2212
|
} finally {
|
|
1565
2213
|
await unlink(mdPath).catch(() => {})
|
|
1566
2214
|
}
|
|
@@ -1595,7 +2243,7 @@ async function activeLibrary() {
|
|
|
1595
2243
|
await writeFile(mdPath, markdown, 'utf8')
|
|
1596
2244
|
const out = join(dir, `${name.slice(0, name.length - 4)}_translated.pdf`)
|
|
1597
2245
|
try {
|
|
1598
|
-
await renderMarkdown(options.md2texScript, mdPath, out, { MATH_DESK_NO_TITLE: '1' })
|
|
2246
|
+
await renderMarkdown(options.md2texScript, mdPath, out, { ...engineToolEnv(options), MATH_DESK_NO_TITLE: '1' })
|
|
1599
2247
|
} finally {
|
|
1600
2248
|
await unlink(mdPath).catch(() => {})
|
|
1601
2249
|
}
|
|
@@ -1734,6 +2382,7 @@ async function activeLibrary() {
|
|
|
1734
2382
|
await mkdir(trash, { recursive: true })
|
|
1735
2383
|
const target = join(trash, `${Date.now()}-${book}`)
|
|
1736
2384
|
await rename(source, target)
|
|
2385
|
+
invalidateCatalog()
|
|
1737
2386
|
sendJson(response, 200, { ok: true, path: target })
|
|
1738
2387
|
return
|
|
1739
2388
|
}
|
|
@@ -1765,67 +2414,251 @@ async function activeLibrary() {
|
|
|
1765
2414
|
return
|
|
1766
2415
|
}
|
|
1767
2416
|
|
|
1768
|
-
|
|
2417
|
+
// Empties one library's `回收站`. Deleting a book only moves it there, so
|
|
2418
|
+
// the folder is the one place where user documents pile up; it is emptied
|
|
2419
|
+
// only on an explicit, confirmed click.
|
|
2420
|
+
if (path === `${PREFIX}/trash/empty`) {
|
|
1769
2421
|
if (request.method !== 'POST') {
|
|
1770
2422
|
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
1771
2423
|
return
|
|
1772
2424
|
}
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
fail(response, 400, 'bad-name', '只接受 md / markdown / txt / pdf 文件')
|
|
2425
|
+
if (!isSameOrigin(request)) {
|
|
2426
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
1776
2427
|
return
|
|
1777
2428
|
}
|
|
1778
|
-
const library = await
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
2429
|
+
const library = await requireLibrary(response)
|
|
2430
|
+
if (library === null) return
|
|
2431
|
+
try {
|
|
2432
|
+
const result = await emptyTrash(library)
|
|
2433
|
+
sendJson(response, 200, { ok: true, ...result })
|
|
2434
|
+
} catch (error) {
|
|
2435
|
+
fail(response, 500, 'trash-empty-failed', String(error && error.message ? error.message : error))
|
|
2436
|
+
}
|
|
2437
|
+
return
|
|
2438
|
+
}
|
|
2439
|
+
|
|
2440
|
+
if (path === `${PREFIX}/imports`) {
|
|
2441
|
+
if (request.method !== 'POST') {
|
|
2442
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
2443
|
+
return
|
|
2444
|
+
}
|
|
2445
|
+
if (!isSameOrigin(request)) {
|
|
2446
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
2447
|
+
return
|
|
2448
|
+
}
|
|
2449
|
+
const kind = url.searchParams.get('kind') ?? ''
|
|
2450
|
+
const name = url.searchParams.get('name') ?? ''
|
|
2451
|
+
const target = url.searchParams.get('target') === 'whole' ? 'whole' : 'fragment'
|
|
2452
|
+
const wantedStrategy = url.searchParams.get('strategy') ?? ''
|
|
2453
|
+
const strategy = wantedStrategy === 'overwrite' || wantedStrategy === 'skip' ? wantedStrategy : 'merge'
|
|
2454
|
+
const subdir = url.searchParams.get('subdir') ?? ''
|
|
2455
|
+
let received = null
|
|
2456
|
+
try {
|
|
2457
|
+
if (kind === 'pdf' || kind === 'md') {
|
|
2458
|
+
const library = await requireLibrary(response)
|
|
2459
|
+
if (library === null) return
|
|
2460
|
+
const extension = extname(String(name)).toLowerCase()
|
|
2461
|
+
// A whole-book PDF over the normal ceiling is allowed only when the
|
|
2462
|
+
// user already accepted the "split it first" warning: the client
|
|
2463
|
+
// sends allowLarge=1 after the second confirmation.
|
|
2464
|
+
const allowLarge = kind === 'pdf' && url.searchParams.get('allowLarge') === '1'
|
|
2465
|
+
const uploadLimit = allowLarge ? MAX_ARCHIVE_FILE_BYTES : MAX_UPLOAD_BYTES
|
|
2466
|
+
received = await receiveUpload(request, {
|
|
2467
|
+
dataDir: config.dataDir,
|
|
2468
|
+
limit: uploadLimit,
|
|
2469
|
+
extension: kind === 'pdf' ? '.pdf' : (['.md', '.markdown', '.txt'].includes(extension) ? extension : ''),
|
|
2470
|
+
})
|
|
2471
|
+
const report = await importSingle({
|
|
2472
|
+
targetDir: join(library.libraryDir, '整本'),
|
|
2473
|
+
dataDir: config.dataDir,
|
|
2474
|
+
name,
|
|
2475
|
+
kind,
|
|
2476
|
+
sourcePath: received.path,
|
|
2477
|
+
maxBytes: uploadLimit,
|
|
2478
|
+
render: options.md2texScript === undefined
|
|
2479
|
+
? undefined
|
|
2480
|
+
: (source, out) => renderMarkdown(options.md2texScript, source, out, engineToolEnv(options)),
|
|
2481
|
+
})
|
|
2482
|
+
received = null
|
|
2483
|
+
invalidateCatalog()
|
|
2484
|
+
const first = report.imported[0] ?? null
|
|
2485
|
+
const duplicate = report.duplicates[0] ?? null
|
|
2486
|
+
sendJson(response, 200, {
|
|
2487
|
+
ok: true,
|
|
2488
|
+
report,
|
|
2489
|
+
...(first === null ? {} : { path: first.path, pdf: first.path, bytes: first.bytes }),
|
|
2490
|
+
...(first === null && duplicate !== null
|
|
2491
|
+
? { path: join(report.targetDir, duplicate.existing), pdf: join(report.targetDir, duplicate.existing), bytes: 0, duplicate: true }
|
|
2492
|
+
: {}),
|
|
2493
|
+
})
|
|
1787
2494
|
return
|
|
1788
2495
|
}
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
for (let n = 2; n < 1000; n += 1) {
|
|
1796
|
-
try {
|
|
1797
|
-
await stat(target)
|
|
1798
|
-
} catch {
|
|
1799
|
-
return target
|
|
2496
|
+
if (kind === 'book-zip') {
|
|
2497
|
+
const library = await requireLibrary(response)
|
|
2498
|
+
if (library === null) return
|
|
2499
|
+
if (/(^|[\\/])\.\.([\\/]|$)/.test(subdir)) {
|
|
2500
|
+
fail(response, 400, 'invalid-subdir', '子目录不能包含 ..')
|
|
2501
|
+
return
|
|
1800
2502
|
}
|
|
1801
|
-
|
|
2503
|
+
const parts = subdir.split(/[\\/]+/).filter(part => part !== '' && part !== '.' && part !== '..')
|
|
2504
|
+
const base = target === 'whole'
|
|
2505
|
+
? join(library.libraryDir, '整本')
|
|
2506
|
+
: (typeof library.fragmentDir === 'string' && library.fragmentDir !== '' ? library.fragmentDir : join(library.libraryDir, '分片'))
|
|
2507
|
+
received = await receiveUpload(request, { dataDir: config.dataDir, limit: MAX_ARCHIVE_TOTAL_BYTES, extension: '.zip' })
|
|
2508
|
+
const report = await importArchive({
|
|
2509
|
+
archivePath: received.path,
|
|
2510
|
+
targetDir: parts.length === 0 ? base : join(base, ...parts),
|
|
2511
|
+
strategy,
|
|
2512
|
+
})
|
|
2513
|
+
invalidateCatalog()
|
|
2514
|
+
sendJson(response, 200, { ok: true, report })
|
|
2515
|
+
return
|
|
2516
|
+
}
|
|
2517
|
+
if (kind === 'migration') {
|
|
2518
|
+
received = await receiveUpload(request, { dataDir: config.dataDir, limit: MAX_ARCHIVE_TOTAL_BYTES, extension: '.zip' })
|
|
2519
|
+
await checkArchiveFile(received.path)
|
|
2520
|
+
const verified = await readBackup(received.path)
|
|
2521
|
+
const path = received.path
|
|
2522
|
+
const bytes = received.bytes
|
|
2523
|
+
// The client imports it next through /backup; that route deletes the file.
|
|
2524
|
+
received = null
|
|
2525
|
+
sendJson(response, 200, { ok: true, path, bytes, manifest: backupSummary(verified) })
|
|
2526
|
+
return
|
|
1802
2527
|
}
|
|
1803
|
-
|
|
2528
|
+
fail(response, 400, 'bad-kind', '未知的导入类型(kind 应为 pdf / md / book-zip / migration)')
|
|
2529
|
+
} catch (error) {
|
|
2530
|
+
const code = error instanceof RejectError ? error.code : (kind === 'migration' ? 'bad-archive' : 'import-failed')
|
|
2531
|
+
const status = error instanceof RejectError ? rejectStatus(code) : (kind === 'migration' ? 400 : 500)
|
|
2532
|
+
fail(response, status, code, String(error && error.message ? error.message : error))
|
|
2533
|
+
} finally {
|
|
2534
|
+
if (received !== null) await rm(received.path, { force: true }).catch(() => {})
|
|
1804
2535
|
}
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
2536
|
+
return
|
|
2537
|
+
}
|
|
2538
|
+
|
|
2539
|
+
// Book-import wizard: stage each package once, inspect it, then apply the
|
|
2540
|
+
// ticked books. Staging keeps the raw uploads out of the request that does
|
|
2541
|
+
// the work, so a slow inspect cannot cut the upload short.
|
|
2542
|
+
if (path === `${PREFIX}/imports/stage`) {
|
|
2543
|
+
if (request.method !== 'POST') {
|
|
2544
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
1809
2545
|
return
|
|
1810
2546
|
}
|
|
1811
|
-
if (
|
|
1812
|
-
fail(response,
|
|
2547
|
+
if (!isSameOrigin(request)) {
|
|
2548
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
1813
2549
|
return
|
|
1814
2550
|
}
|
|
1815
|
-
const
|
|
1816
|
-
await mkdir(
|
|
1817
|
-
|
|
1818
|
-
const
|
|
2551
|
+
const tmpDir = join(config.dataDir, 'tmp')
|
|
2552
|
+
await mkdir(tmpDir, { recursive: true })
|
|
2553
|
+
// Two hours are plenty to finish a wizard; older stage files are dead.
|
|
2554
|
+
for (const name of await readdir(tmpDir).catch(() => [])) {
|
|
2555
|
+
if (!/^stage-[0-9a-f-]{36}\.zip$/.test(name)) continue
|
|
2556
|
+
const info = await stat(join(tmpDir, name)).catch(() => null)
|
|
2557
|
+
if (info !== null && Date.now() - info.mtimeMs > 2 * 60 * 60 * 1000) {
|
|
2558
|
+
await rm(join(tmpDir, name), { force: true }).catch(() => {})
|
|
2559
|
+
}
|
|
2560
|
+
}
|
|
2561
|
+
let received = null
|
|
1819
2562
|
try {
|
|
1820
|
-
await
|
|
2563
|
+
received = await receiveUpload(request, { dataDir: config.dataDir, limit: MAX_ARCHIVE_TOTAL_BYTES, extension: '.zip' })
|
|
2564
|
+
await checkArchiveFile(received.path)
|
|
2565
|
+
const token = `stage-${randomUUID()}.zip`
|
|
2566
|
+
await rename(received.path, join(tmpDir, token))
|
|
2567
|
+
received = null
|
|
2568
|
+
sendJson(response, 200, { ok: true, token })
|
|
1821
2569
|
} catch (error) {
|
|
1822
|
-
|
|
2570
|
+
const code = error instanceof RejectError ? error.code : 'stage-failed'
|
|
2571
|
+
fail(response, error instanceof RejectError ? rejectStatus(code) : 400, code, String(error && error.message ? error.message : error))
|
|
2572
|
+
} finally {
|
|
2573
|
+
if (received !== null) await rm(received.path, { force: true }).catch(() => {})
|
|
2574
|
+
}
|
|
2575
|
+
return
|
|
2576
|
+
}
|
|
2577
|
+
|
|
2578
|
+
if (path === `${PREFIX}/book-import/inspect`) {
|
|
2579
|
+
if (request.method !== 'POST') {
|
|
2580
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
2581
|
+
return
|
|
2582
|
+
}
|
|
2583
|
+
const body = await mutationBody(request, response)
|
|
2584
|
+
if (body === undefined) return
|
|
2585
|
+
const record = body !== null && typeof body === 'object' ? body : {}
|
|
2586
|
+
const library = await requireLibrary(response)
|
|
2587
|
+
if (library === null) return
|
|
2588
|
+
const pdfPath = stagedPath(record.pdf)
|
|
2589
|
+
if (pdfPath === null) {
|
|
2590
|
+
fail(response, 400, 'bad-package', '请先选择 PDF 包')
|
|
1823
2591
|
return
|
|
1824
2592
|
}
|
|
1825
|
-
|
|
2593
|
+
const notesPath = record.notes === undefined || record.notes === null || record.notes === '' ? null : stagedPath(record.notes)
|
|
2594
|
+
if (notesPath === null && record.notes !== undefined && record.notes !== null && record.notes !== '') {
|
|
2595
|
+
fail(response, 400, 'bad-notes', '笔记包无效,请重新选择')
|
|
2596
|
+
return
|
|
2597
|
+
}
|
|
2598
|
+
if (await stat(pdfPath).catch(() => null) === null) {
|
|
2599
|
+
fail(response, 404, 'missing-package', 'PDF 包已过期,请重新选择')
|
|
2600
|
+
return
|
|
2601
|
+
}
|
|
2602
|
+
if (notesPath !== null && await stat(notesPath).catch(() => null) === null) {
|
|
2603
|
+
fail(response, 404, 'missing-notes', '笔记包已过期,请重新选择')
|
|
2604
|
+
return
|
|
2605
|
+
}
|
|
2606
|
+
try {
|
|
2607
|
+
const result = await inspectBookPack({
|
|
2608
|
+
archivePath: pdfPath,
|
|
2609
|
+
...(notesPath === null ? {} : { notesPath }),
|
|
2610
|
+
libraryDir: library.libraryDir,
|
|
2611
|
+
})
|
|
2612
|
+
sendJson(response, 200, { ok: true, ...result })
|
|
2613
|
+
} catch (error) {
|
|
2614
|
+
fail(response, 400, 'bad-package', String(error && error.message ? error.message : error))
|
|
2615
|
+
}
|
|
1826
2616
|
return
|
|
1827
2617
|
}
|
|
1828
2618
|
|
|
2619
|
+
if (path === `${PREFIX}/book-import/apply`) {
|
|
2620
|
+
if (request.method !== 'POST') {
|
|
2621
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
2622
|
+
return
|
|
2623
|
+
}
|
|
2624
|
+
const body = await mutationBody(request, response)
|
|
2625
|
+
if (body === undefined) return
|
|
2626
|
+
const record = body !== null && typeof body === 'object' ? body : {}
|
|
2627
|
+
const library = await requireLibrary(response)
|
|
2628
|
+
if (library === null) return
|
|
2629
|
+
const pdfPath = stagedPath(record.pdf)
|
|
2630
|
+
if (pdfPath === null) {
|
|
2631
|
+
fail(response, 400, 'bad-package', '请先选择 PDF 包')
|
|
2632
|
+
return
|
|
2633
|
+
}
|
|
2634
|
+
const notesPath = record.notes === undefined || record.notes === null || record.notes === '' ? null : stagedPath(record.notes)
|
|
2635
|
+
if (notesPath === null && record.notes !== undefined && record.notes !== null && record.notes !== '') {
|
|
2636
|
+
fail(response, 400, 'bad-notes', '笔记包无效,请重新选择')
|
|
2637
|
+
return
|
|
2638
|
+
}
|
|
2639
|
+
try {
|
|
2640
|
+
const result = await applyBookPack({
|
|
2641
|
+
archivePath: pdfPath,
|
|
2642
|
+
...(notesPath === null ? {} : { notesPath }),
|
|
2643
|
+
libraryDir: library.libraryDir,
|
|
2644
|
+
selection: Array.isArray(record.books) ? record.books : [],
|
|
2645
|
+
})
|
|
2646
|
+
invalidateCatalog()
|
|
2647
|
+
sendJson(response, 200, { ok: true, ...result })
|
|
2648
|
+
} catch (error) {
|
|
2649
|
+
fail(response, 500, 'book-import-failed', String(error && error.message ? error.message : error))
|
|
2650
|
+
} finally {
|
|
2651
|
+
await discardStage(pdfPath)
|
|
2652
|
+
if (notesPath !== null) await discardStage(notesPath)
|
|
2653
|
+
}
|
|
2654
|
+
return
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
// One version of compatibility: the old browser-upload route forwards to
|
|
2658
|
+
// the unified pipeline and keeps its response shape for older pages.
|
|
2659
|
+
// `/import` and `/library-import` were the pre-v1.5 upload routes, kept one
|
|
2660
|
+
// release as thin wrappers. The client has used `/imports` since v1.5 and
|
|
2661
|
+
// the compatibility window is over: both routes are gone in this release.
|
|
1829
2662
|
if (path === `${PREFIX}/samples`) {
|
|
1830
2663
|
if (request.method !== 'GET') {
|
|
1831
2664
|
fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
|
|
@@ -1874,6 +2707,7 @@ async function activeLibrary() {
|
|
|
1874
2707
|
skipped += 1
|
|
1875
2708
|
}
|
|
1876
2709
|
}
|
|
2710
|
+
invalidateCatalog()
|
|
1877
2711
|
sendJson(response, 200, { ok: true, book: bookId, dir: target, copied, skipped })
|
|
1878
2712
|
return
|
|
1879
2713
|
}
|
|
@@ -2218,18 +3052,84 @@ async function activeLibrary() {
|
|
|
2218
3052
|
return
|
|
2219
3053
|
}
|
|
2220
3054
|
for (const [extension, contentType] of Object.entries(COVER_TYPES)) {
|
|
3055
|
+
const path = join((await activeLibrary()).coverDir, `${bookId}.${extension}`)
|
|
3056
|
+
const info = await stat(path).catch(() => null)
|
|
3057
|
+
if (info === null || !info.isFile()) continue
|
|
3058
|
+
// Cover images repeat on every shelf render, so they get an entity tag
|
|
3059
|
+
// and a short private cache instead of the server's usual `no-store`.
|
|
3060
|
+
const etag = `"${info.size.toString(36)}-${Math.floor(info.mtimeMs).toString(36)}"`
|
|
3061
|
+
if (sendNotModified(request, response, etag)) return
|
|
2221
3062
|
try {
|
|
2222
|
-
const body = await readFile(
|
|
2223
|
-
sendBytes(response, 200, body, contentType)
|
|
3063
|
+
const body = await readFile(path)
|
|
3064
|
+
sendBytes(response, 200, body, contentType, undefined, { etag, maxAge: 300 })
|
|
2224
3065
|
return
|
|
2225
3066
|
} catch {
|
|
2226
|
-
//
|
|
3067
|
+
// A cover that vanished between stat and read is simply absent.
|
|
2227
3068
|
}
|
|
2228
3069
|
}
|
|
2229
3070
|
fail(response, 404, 'no-cover', '这本书没有自定义封面')
|
|
2230
3071
|
return
|
|
2231
3072
|
}
|
|
2232
3073
|
|
|
3074
|
+
// The model inventory this deployment can route, for the settings page.
|
|
3075
|
+
// Read-only: it never selects a model and never writes the default.
|
|
3076
|
+
if (path === `${PREFIX}/ai-catalog`) {
|
|
3077
|
+
if (request.method !== 'GET') {
|
|
3078
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
|
|
3079
|
+
return
|
|
3080
|
+
}
|
|
3081
|
+
const catalog = typeof options.aiCatalog === 'function' ? await options.aiCatalog() : null
|
|
3082
|
+
sendJson(response, 200, {
|
|
3083
|
+
ok: true,
|
|
3084
|
+
providers: catalog === null || catalog === undefined ? [] : catalog.providers,
|
|
3085
|
+
default: catalog === null || catalog === undefined ? null : catalog.default,
|
|
3086
|
+
failures: catalog === null || catalog === undefined ? [] : catalog.failures,
|
|
3087
|
+
})
|
|
3088
|
+
return
|
|
3089
|
+
}
|
|
3090
|
+
|
|
3091
|
+
// Create one reader session with an explicit model. The model is creation
|
|
3092
|
+
// options only; the deployment default is never written.
|
|
3093
|
+
if (path === `${PREFIX}/ai-session`) {
|
|
3094
|
+
if (request.method !== 'POST') {
|
|
3095
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
3096
|
+
return
|
|
3097
|
+
}
|
|
3098
|
+
try {
|
|
3099
|
+
const body = await readJson(request)
|
|
3100
|
+
const created = typeof options.aiSession === 'function' ? await options.aiSession(body) : null
|
|
3101
|
+
if (created === null) {
|
|
3102
|
+
fail(response, 409, 'ai-unavailable', '宿主没有提供模型会话')
|
|
3103
|
+
return
|
|
3104
|
+
}
|
|
3105
|
+
sendJson(response, 200, { ok: true, sessionId: created.sessionId, selection: created.selection })
|
|
3106
|
+
} catch (error) {
|
|
3107
|
+
fail(response, 400, 'ai-session-failed', String(error !== null && error !== undefined && error.message ? error.message : error))
|
|
3108
|
+
}
|
|
3109
|
+
return
|
|
3110
|
+
}
|
|
3111
|
+
|
|
3112
|
+
// One-click isolation probe: build a throwaway session with the chosen
|
|
3113
|
+
// model and report whether the deployment default moved.
|
|
3114
|
+
if (path === `${PREFIX}/ai-probe`) {
|
|
3115
|
+
if (request.method !== 'POST') {
|
|
3116
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
3117
|
+
return
|
|
3118
|
+
}
|
|
3119
|
+
try {
|
|
3120
|
+
const body = await readJson(request)
|
|
3121
|
+
const result = typeof options.aiProbe === 'function' ? await options.aiProbe(body) : null
|
|
3122
|
+
if (result === null) {
|
|
3123
|
+
fail(response, 409, 'ai-unavailable', '宿主没有提供模型会话')
|
|
3124
|
+
return
|
|
3125
|
+
}
|
|
3126
|
+
sendJson(response, 200, { ok: true, ...result })
|
|
3127
|
+
} catch (error) {
|
|
3128
|
+
fail(response, 400, 'ai-probe-failed', String(error !== null && error !== undefined && error.message ? error.message : error))
|
|
3129
|
+
}
|
|
3130
|
+
return
|
|
3131
|
+
}
|
|
3132
|
+
|
|
2233
3133
|
if (path === `${PREFIX}/context`) {
|
|
2234
3134
|
if (request.method !== 'GET') {
|
|
2235
3135
|
fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
|