@steerable/steer 0.0.0-stage → 0.3.13

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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -2
  3. package/bin/steer.js +2 -0
  4. package/dist/packages/doc-preview/src/assemble.js +183 -0
  5. package/dist/packages/doc-preview/src/edit-failure.js +116 -0
  6. package/dist/packages/doc-preview/src/edit-service.js +879 -0
  7. package/dist/packages/doc-preview/src/edit.js +437 -0
  8. package/dist/packages/doc-preview/src/export.js +540 -0
  9. package/dist/packages/doc-preview/src/index.js +5 -0
  10. package/dist/packages/doc-preview/src/migrations.js +77 -0
  11. package/dist/packages/doc-preview/src/office-converter.js +186 -0
  12. package/dist/packages/doc-preview/src/office-file-preview.js +457 -0
  13. package/dist/packages/doc-preview/src/office-media.js +80 -0
  14. package/dist/packages/doc-preview/src/office-raster.js +146 -0
  15. package/dist/packages/doc-preview/src/office-routes.js +191 -0
  16. package/dist/packages/doc-preview/src/office-runtime.js +251 -0
  17. package/dist/packages/doc-preview/src/preview.js +296 -0
  18. package/dist/packages/doc-preview/src/render.js +351 -0
  19. package/dist/packages/doc-preview/src/routes.js +376 -0
  20. package/dist/packages/doc-preview/src/settings.js +58 -0
  21. package/dist/packages/doc-preview/src/store.js +134 -0
  22. package/dist/packages/doc-preview/src/tasks.js +16 -0
  23. package/dist/packages/doc-preview/src/word-font.js +232 -0
  24. package/dist/packages/doc-preview/src/word-preview.js +292 -0
  25. package/dist/packages/doc-preview/src/word-render.js +283 -0
  26. package/dist/packages/doc-preview/src/word-routes.js +203 -0
  27. package/dist/packages/doc-preview/src/workspace.js +100 -0
  28. package/dist/products/bundled-python.js +110 -0
  29. package/dist/products/load-locale.js +38 -0
  30. package/dist/products/manifest.json +13 -0
  31. package/dist/products/node-gate.js +132 -0
  32. package/dist/products/steer/active.js +93 -0
  33. package/dist/products/steer/browser-detect.js +230 -0
  34. package/dist/products/steer/browser-protocol.js +2 -0
  35. package/dist/products/steer/browser-session.js +811 -0
  36. package/dist/products/steer/browser.js +521 -0
  37. package/dist/products/steer/cli-main.js +13 -0
  38. package/dist/products/steer/cli.js +8 -0
  39. package/dist/products/steer/computer-macos.js +126 -0
  40. package/dist/products/steer/computer-session.js +118 -0
  41. package/dist/products/steer/computer.js +186 -0
  42. package/dist/products/steer/file-preview.js +392 -0
  43. package/dist/products/steer/locales/shell.zh.json +1120 -0
  44. package/dist/products/steer/locales/zh.json +95 -0
  45. package/dist/products/steer/markdown-preview.js +139 -0
  46. package/dist/products/steer/migrate-legacy-data.js +238 -0
  47. package/dist/products/steer/permissions.js +174 -0
  48. package/dist/products/steer/product.json +85 -0
  49. package/dist/products/steer/server.js +8 -0
  50. package/dist/products/steer/skill-read.js +105 -0
  51. package/dist/products/steer/turn-changes.js +187 -0
  52. package/package.json +38 -4
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Office -> PDF 转换执行器:
3
+ * 1. 复用持久化的 LibreOffice 配置槽位(lo-profile-<slot>),省去每次冷启动建 profile 的开销;
4
+ * 2. 有限并发队列(默认 2 槽位),同文件按单飞锁去重;
5
+ * 3. 看门狗超时强杀(SIGTERM -> SIGKILL)并自动清理锁文件、重建槽位,确保坏文件不污染后续转换;
6
+ * 4. 若本机或托管引擎均不存在,抛出 OfficeEngineMissingError(424 / ENGINE_MISSING)。
7
+ */
8
+ import { spawn } from 'node:child_process';
9
+ import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
10
+ import path from 'node:path';
11
+ import { getUserDataDir } from '@steerable/agent-shell/runtime';
12
+ import { resolveOfficeEngine } from './office-runtime.js';
13
+ const DEFAULT_TIMEOUT_MS = 60_000;
14
+ const KILL_GRACE_MS = 1_000;
15
+ const DEFAULT_CONCURRENCY = 2;
16
+ export class OfficeEngineMissingError extends Error {
17
+ status = 424;
18
+ code = 'ENGINE_MISSING';
19
+ constructor(message = '未检测到本地排版引擎。可一键下载本地引擎,或用「打开」以系统默认应用查看。') {
20
+ super(message);
21
+ this.name = 'OfficeEngineMissingError';
22
+ }
23
+ }
24
+ function cleanProfileLocks(profileDir) {
25
+ if (!existsSync(profileDir))
26
+ return;
27
+ try {
28
+ for (const name of readdirSync(profileDir)) {
29
+ if (name.startsWith('.~lock')) {
30
+ rmSync(path.join(profileDir, name), { force: true });
31
+ }
32
+ }
33
+ }
34
+ catch {
35
+ // 忽略清理锁文件时的临时竞争
36
+ }
37
+ }
38
+ function fileUrl(dirPath) {
39
+ const normalized = path.resolve(dirPath).replace(/\\/g, '/');
40
+ return normalized.startsWith('/') ? `file://${normalized}` : `file:///${normalized}`;
41
+ }
42
+ export async function runSofficeConvert(input) {
43
+ mkdirSync(input.profileDir, { recursive: true });
44
+ cleanProfileLocks(input.profileDir);
45
+ await new Promise((resolve, reject) => {
46
+ const child = spawn(input.sofficePath, [
47
+ `-env:UserInstallation=${fileUrl(input.profileDir)}`,
48
+ '--headless',
49
+ '--norestore',
50
+ '--nodefault',
51
+ '--nofirststartwizard',
52
+ '--convert-to',
53
+ 'pdf',
54
+ '--outdir',
55
+ input.outDir,
56
+ input.inputPath,
57
+ ], {
58
+ stdio: ['ignore', 'pipe', 'pipe'],
59
+ env: {
60
+ ...process.env,
61
+ HOME: input.profileDir,
62
+ XDG_CACHE_HOME: path.join(input.profileDir, 'cache'),
63
+ XDG_CONFIG_HOME: path.join(input.profileDir, 'config'),
64
+ },
65
+ });
66
+ let stdout = '';
67
+ let stderr = '';
68
+ let timedOut = false;
69
+ let settled = false;
70
+ let killTimer = null;
71
+ child.stdout.on('data', (chunk) => {
72
+ if (stdout.length < 32_768)
73
+ stdout += chunk.toString('utf8');
74
+ });
75
+ child.stderr.on('data', (chunk) => {
76
+ if (stderr.length < 32_768)
77
+ stderr += chunk.toString('utf8');
78
+ });
79
+ const timeoutTimer = setTimeout(() => {
80
+ timedOut = true;
81
+ child.kill('SIGTERM');
82
+ killTimer = setTimeout(() => {
83
+ if (!settled)
84
+ child.kill('SIGKILL');
85
+ }, KILL_GRACE_MS);
86
+ }, input.timeoutMs);
87
+ const finish = (err) => {
88
+ if (settled)
89
+ return;
90
+ settled = true;
91
+ clearTimeout(timeoutTimer);
92
+ if (killTimer)
93
+ clearTimeout(killTimer);
94
+ if (err)
95
+ reject(err);
96
+ else
97
+ resolve();
98
+ };
99
+ child.once('error', (err) => {
100
+ finish(err);
101
+ });
102
+ child.once('close', (code, signal) => {
103
+ if (timedOut) {
104
+ // 超时被杀后清理可能损坏的 profile 锁,下次请求直接恢复
105
+ rmSync(input.profileDir, { recursive: true, force: true });
106
+ finish(new Error(`转换超时(>${Math.round(input.timeoutMs / 1000)}s),已自动终止以保护系统`));
107
+ return;
108
+ }
109
+ if (code === 0) {
110
+ finish();
111
+ return;
112
+ }
113
+ const detail = [stderr.trim(), stdout.trim()].filter(Boolean).join('\n');
114
+ finish(new Error(detail || `LibreOffice 退出异常 (${signal ?? code ?? 'unknown'})`));
115
+ });
116
+ });
117
+ }
118
+ export class OfficeConverter {
119
+ maxConcurrent;
120
+ timeoutMs;
121
+ profileBaseDir;
122
+ resolveEngine;
123
+ runner;
124
+ busySlots = new Set();
125
+ waiters = [];
126
+ constructor(options) {
127
+ this.maxConcurrent = Math.max(1, options?.maxConcurrent ?? DEFAULT_CONCURRENCY);
128
+ this.timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
129
+ this.profileBaseDir = options?.profileBaseDir;
130
+ this.resolveEngine = options?.resolveEngine ?? resolveOfficeEngine;
131
+ this.runner = options?.runner ?? runSofficeConvert;
132
+ }
133
+ acquireSlot() {
134
+ for (let slot = 0; slot < this.maxConcurrent; slot += 1) {
135
+ if (!this.busySlots.has(slot)) {
136
+ this.busySlots.add(slot);
137
+ return Promise.resolve(slot);
138
+ }
139
+ }
140
+ return new Promise((resolve) => {
141
+ this.waiters.push(resolve);
142
+ });
143
+ }
144
+ releaseSlot(slot) {
145
+ const next = this.waiters.shift();
146
+ if (next) {
147
+ next(slot);
148
+ return;
149
+ }
150
+ this.busySlots.delete(slot);
151
+ }
152
+ async convertToPdf(inputPath, outDir) {
153
+ const engine = this.resolveEngine();
154
+ if (!engine) {
155
+ throw new OfficeEngineMissingError();
156
+ }
157
+ const slot = await this.acquireSlot();
158
+ const baseDir = this.profileBaseDir ?? path.join(getUserDataDir(), 'office-previews', 'profiles');
159
+ const profileDir = path.join(baseDir, `lo-slot-${slot}`);
160
+ try {
161
+ await this.runner({
162
+ sofficePath: engine.sofficePath,
163
+ inputPath,
164
+ outDir,
165
+ profileDir,
166
+ timeoutMs: this.timeoutMs,
167
+ });
168
+ const pdfName = readdirSync(outDir).find((name) => name.toLowerCase().endsWith('.pdf'));
169
+ if (!pdfName) {
170
+ throw new Error('排版引擎未生成 PDF,请检查该文件是否损坏或加密');
171
+ }
172
+ return path.join(outDir, pdfName);
173
+ }
174
+ catch (err) {
175
+ const code = err?.code;
176
+ if (code === 'ENOENT') {
177
+ throw new OfficeEngineMissingError();
178
+ }
179
+ throw err;
180
+ }
181
+ finally {
182
+ this.releaseSlot(slot);
183
+ }
184
+ }
185
+ }
186
+ export const defaultOfficeConverter = new OfficeConverter();
@@ -0,0 +1,457 @@
1
+ /**
2
+ * 把会话里已经交付的 PPT / Word 文件转成逐页 PNG。
3
+ *
4
+ * 设计稿工作区里的 SVG / document.docx 仍走原来的预览。
5
+ * 这里只读回合产物或该会话工作区里的 .ppt/.pptx/.doc/.docx。
6
+ */
7
+ import { execFile } from 'node:child_process';
8
+ import { createHash } from 'node:crypto';
9
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
10
+ import { mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { promisify } from 'node:util';
14
+ import { getUserDataDir } from '@steerable/agent-shell/runtime';
15
+ import { SAFE_CHAT_ID } from './preview.js';
16
+ import { stripOfficeMedia } from './office-media.js';
17
+ import { rasterizePdfDocument, resolveSofficeCommand } from './office-raster.js';
18
+ import { defaultOfficeConverter, OfficeEngineMissingError, } from './office-converter.js';
19
+ const execFileAsync = promisify(execFile);
20
+ const SOFFICE_TIMEOUT_MS = 180_000;
21
+ const PREVIEW_DPI = 110;
22
+ const MAX_PAGES = 40;
23
+ /** 逐页 PNG 路径的上限:每页 base64 都在内存里过一遍,超了就翻不动。 */
24
+ export const MAX_FILE_BYTES = 80 * 1024 * 1024;
25
+ /** PDF 路径的上限:只转 PDF,渲染在 WebView 里按需分片,源文件可以大得多。 */
26
+ export const MAX_PDF_SOURCE_BYTES = 512 * 1024 * 1024;
27
+ const MANIFEST_NAME = 'manifest.json';
28
+ export class OfficePreviewError extends Error {
29
+ status;
30
+ code;
31
+ constructor(status, message, code) {
32
+ super(message);
33
+ this.name = 'OfficePreviewError';
34
+ this.status = status;
35
+ this.code = code;
36
+ }
37
+ }
38
+ const renderLocks = new Map();
39
+ const pdfRenderLocks = new Map();
40
+ /** `.ppt` / `.pptx` → ppt,`.doc` / `.docx` → word。其它扩展名没有预览。 */
41
+ export function officePreviewKind(filePath) {
42
+ const ext = path.extname(filePath).toLowerCase();
43
+ if (ext === '.pptx' || ext === '.ppt')
44
+ return 'ppt';
45
+ if (ext === '.docx' || ext === '.doc')
46
+ return 'word';
47
+ return null;
48
+ }
49
+ function turnFilePaths(raw) {
50
+ if (!raw)
51
+ return [];
52
+ let parsed;
53
+ try {
54
+ parsed = JSON.parse(raw);
55
+ }
56
+ catch {
57
+ return [];
58
+ }
59
+ if (!parsed || typeof parsed !== 'object')
60
+ return [];
61
+ const files = parsed.turnFiles;
62
+ if (!Array.isArray(files))
63
+ return [];
64
+ const found = [];
65
+ for (const item of files) {
66
+ if (!item || typeof item !== 'object')
67
+ continue;
68
+ const filePath = item.path;
69
+ if (typeof filePath === 'string' && filePath)
70
+ found.push(filePath);
71
+ }
72
+ return found;
73
+ }
74
+ function isPathInside(root, target) {
75
+ const relative = path.relative(path.resolve(root), path.resolve(target));
76
+ return relative === '' || (relative !== '..' &&
77
+ !relative.startsWith(`..${path.sep}`) &&
78
+ !path.isAbsolute(relative));
79
+ }
80
+ /**
81
+ * 路径必须写在本会话的回合产物里,或者落在该会话的 PPT / 文件工作区下。
82
+ */
83
+ export function officeFileIsAllowed(input) {
84
+ const teamUserRoot = process.env.DEEPPATH_TEAM_USER_DATA_ROOT?.trim();
85
+ if (teamUserRoot) {
86
+ // 团队版是多租户共享宿主:只认当前用户数据目录 / 本会话工作区,防止
87
+ // 会话产物里的符号链接把 realpath 指向别的用户数据目录。
88
+ return (isPathInside(getUserDataDir(), input.realPath) ||
89
+ input.workspaceRoots.some((root) => isPathInside(root, input.realPath)));
90
+ }
91
+ const wanted = new Set([
92
+ path.resolve(input.requestedPath),
93
+ path.resolve(input.realPath),
94
+ ]);
95
+ for (const message of input.messages) {
96
+ for (const listed of turnFilePaths(message.messageMetadata)) {
97
+ if (wanted.has(path.resolve(listed)))
98
+ return true;
99
+ }
100
+ }
101
+ return input.workspaceRoots.some((root) => isPathInside(root, input.realPath));
102
+ }
103
+ function workspaceRoots(chatId) {
104
+ const root = getUserDataDir();
105
+ return [
106
+ path.join(root, 'ppt-projects', chatId),
107
+ path.join(root, 'files', chatId),
108
+ ];
109
+ }
110
+ /** 确认这个绝对路径可以在该会话里预览。不通过时抛 {@link OfficePreviewError}。 */
111
+ export async function resolveAllowedOfficeFile(input) {
112
+ const chatId = input.chatId.trim();
113
+ if (!SAFE_CHAT_ID.test(chatId)) {
114
+ throw new OfficePreviewError(400, 'chatId 无效');
115
+ }
116
+ const filePath = input.filePath.trim();
117
+ if (!filePath || filePath.includes('\0') || !path.isAbsolute(filePath)) {
118
+ throw new OfficePreviewError(400, '需要文件的绝对路径');
119
+ }
120
+ const kind = officePreviewKind(filePath);
121
+ if (!kind) {
122
+ throw new OfficePreviewError(400, '只能预览 PPT 或 Word 文件');
123
+ }
124
+ let realPath;
125
+ let fileStat;
126
+ try {
127
+ realPath = await realpath(filePath);
128
+ fileStat = await stat(realPath);
129
+ }
130
+ catch {
131
+ throw new OfficePreviewError(404, '找不到这个文件');
132
+ }
133
+ if (!fileStat.isFile()) {
134
+ throw new OfficePreviewError(404, '找不到这个文件');
135
+ }
136
+ if (fileStat.size > (input.maxBytes ?? MAX_FILE_BYTES)) {
137
+ throw new OfficePreviewError(400, '文件太大,无法生成预览');
138
+ }
139
+ if (!officeFileIsAllowed({
140
+ requestedPath: filePath,
141
+ realPath,
142
+ messages: input.messages,
143
+ workspaceRoots: workspaceRoots(chatId),
144
+ })) {
145
+ throw new OfficePreviewError(404, '这个文件不属于当前对话');
146
+ }
147
+ return {
148
+ chatId,
149
+ realPath,
150
+ kind,
151
+ mtimeMs: Math.max(0, Math.round(fileStat.mtimeMs)),
152
+ fileName: path.basename(realPath),
153
+ };
154
+ }
155
+ function cacheDirFor(realPath, mtimeMs) {
156
+ const digest = createHash('sha256')
157
+ .update(realPath)
158
+ .update('\0')
159
+ .update(String(mtimeMs))
160
+ .digest('hex');
161
+ return path.join(getUserDataDir(), 'office-previews', digest);
162
+ }
163
+ function readCachedManifest(dir) {
164
+ const manifestPath = path.join(dir, MANIFEST_NAME);
165
+ if (!existsSync(manifestPath))
166
+ return null;
167
+ try {
168
+ const parsed = JSON.parse(readFileSync(manifestPath, 'utf8'));
169
+ if (!parsed || !Array.isArray(parsed.pages) || parsed.pages.length === 0)
170
+ return null;
171
+ return parsed;
172
+ }
173
+ catch {
174
+ return null;
175
+ }
176
+ }
177
+ function toPublicManifest(target, cached) {
178
+ return {
179
+ fileName: target.fileName,
180
+ kind: target.kind,
181
+ pageCount: cached.pages.length,
182
+ pages: cached.pages.map((page) => ({
183
+ index: page.index,
184
+ width: page.width,
185
+ height: page.height,
186
+ })),
187
+ };
188
+ }
189
+ async function runExec(file, args, options) {
190
+ try {
191
+ await execFileAsync(file, args, {
192
+ timeout: options.timeoutMs,
193
+ maxBuffer: 32 * 1024 * 1024,
194
+ env: options.env,
195
+ });
196
+ }
197
+ catch (err) {
198
+ const error = err;
199
+ if (error.code === 'ENOENT') {
200
+ throw new OfficePreviewError(500, `找不到 ${file},无法生成预览。请安装 LibreOffice 和 poppler(pdftoppm),或用「打开方式」用系统应用打开。`);
201
+ }
202
+ const detail = [error.stderr, error.stdout]
203
+ .map((value) => (value ? value.toString().trim() : ''))
204
+ .filter(Boolean)
205
+ .join('\n');
206
+ throw new OfficePreviewError(500, detail || error.message || `执行 ${file} 失败`);
207
+ }
208
+ }
209
+ function parsePngSize(filePath) {
210
+ const buffer = readFileSync(filePath);
211
+ if (buffer.length < 24)
212
+ return null;
213
+ return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
214
+ }
215
+ function listRasterPages(dir) {
216
+ return readdirSync(dir)
217
+ .filter((name) => /^page-\d+\.png$/i.test(name))
218
+ .sort((left, right) => {
219
+ const leftNumber = Number(left.match(/\d+/)?.[0] ?? 0);
220
+ const rightNumber = Number(right.match(/\d+/)?.[0] ?? 0);
221
+ return leftNumber - rightNumber;
222
+ });
223
+ }
224
+ async function renderOfficeFile(target) {
225
+ const previewDir = cacheDirFor(target.realPath, target.mtimeMs);
226
+ const existing = readCachedManifest(previewDir);
227
+ if (existing?.sourcePath === target.realPath && existing.mtimeMs === target.mtimeMs) {
228
+ return existing;
229
+ }
230
+ const pending = renderLocks.get(previewDir);
231
+ if (pending)
232
+ return pending;
233
+ const task = renderOfficeFileUncached(target, previewDir).finally(() => {
234
+ if (renderLocks.get(previewDir) === task)
235
+ renderLocks.delete(previewDir);
236
+ });
237
+ renderLocks.set(previewDir, task);
238
+ return task;
239
+ }
240
+ async function renderOfficeFileUncached(target, previewDir) {
241
+ const again = readCachedManifest(previewDir);
242
+ if (again?.sourcePath === target.realPath && again.mtimeMs === target.mtimeMs)
243
+ return again;
244
+ mkdirSync(previewDir, { recursive: true });
245
+ const tmpDir = await mkdtemp(path.join(os.tmpdir(), 'office-preview-'));
246
+ const profileDir = path.join(tmpDir, 'lo-profile');
247
+ mkdirSync(profileDir, { recursive: true });
248
+ try {
249
+ const soffice = resolveSofficeCommand();
250
+ await runExec(soffice, [
251
+ `-env:UserInstallation=file://${profileDir}`,
252
+ '--headless',
253
+ '--norestore',
254
+ '--convert-to',
255
+ 'pdf',
256
+ '--outdir',
257
+ tmpDir,
258
+ target.realPath,
259
+ ], {
260
+ timeoutMs: SOFFICE_TIMEOUT_MS,
261
+ env: {
262
+ ...process.env,
263
+ HOME: tmpDir,
264
+ XDG_CACHE_HOME: path.join(tmpDir, 'cache'),
265
+ XDG_CONFIG_HOME: path.join(tmpDir, 'config'),
266
+ },
267
+ });
268
+ const pdfName = readdirSync(tmpDir).find((name) => name.toLowerCase().endsWith('.pdf'));
269
+ if (!pdfName) {
270
+ throw new OfficePreviewError(500, 'LibreOffice 没有生成 PDF,请检查这个文件是否能打开');
271
+ }
272
+ for (const name of readdirSync(previewDir)) {
273
+ if (/^page-\d+\.png$/i.test(name))
274
+ rmSync(path.join(previewDir, name), { force: true });
275
+ }
276
+ await rasterizePdfDocument({
277
+ pdfPath: path.join(tmpDir, pdfName),
278
+ previewDir,
279
+ dpi: PREVIEW_DPI,
280
+ maxPages: MAX_PAGES,
281
+ });
282
+ const rasterPages = listRasterPages(previewDir);
283
+ const pages = [];
284
+ for (let index = 0; index < rasterPages.length; index += 1) {
285
+ const sourcePath = path.join(previewDir, rasterPages[index]);
286
+ const file = `page-${String(index + 1).padStart(3, '0')}.png`;
287
+ const targetPath = path.join(previewDir, file);
288
+ if (sourcePath !== targetPath)
289
+ renameSync(sourcePath, targetPath);
290
+ const size = parsePngSize(targetPath);
291
+ pages.push({
292
+ index: index + 1,
293
+ file,
294
+ width: size?.width ?? 0,
295
+ height: size?.height ?? 0,
296
+ });
297
+ }
298
+ if (pages.length === 0) {
299
+ throw new OfficePreviewError(500, '没有生成预览页。请确认本机有 LibreOffice 和 pdftoppm。');
300
+ }
301
+ const cached = {
302
+ sourcePath: target.realPath,
303
+ mtimeMs: target.mtimeMs,
304
+ kind: target.kind,
305
+ pages,
306
+ };
307
+ writeFileSync(path.join(previewDir, MANIFEST_NAME), JSON.stringify(cached), 'utf8');
308
+ return cached;
309
+ }
310
+ finally {
311
+ await rm(tmpDir, { recursive: true, force: true });
312
+ }
313
+ }
314
+ /** 生成(或复用缓存)并返回页码清单,不含图片字节。 */
315
+ export async function ensureOfficeFilePreview(target) {
316
+ const cached = await renderOfficeFile(target);
317
+ return toPublicManifest(target, cached);
318
+ }
319
+ /** 读取一页 PNG。页码从 1 开始。 */
320
+ export async function readOfficeFilePreviewPage(target, page) {
321
+ if (!Number.isInteger(page) || page < 1) {
322
+ throw new OfficePreviewError(400, '页码无效');
323
+ }
324
+ const cached = await renderOfficeFile(target);
325
+ const found = cached.pages.find((item) => item.index === page);
326
+ if (!found)
327
+ throw new OfficePreviewError(404, '没有这一页');
328
+ const filePath = path.join(cacheDirFor(target.realPath, target.mtimeMs), found.file);
329
+ const buffer = await readFile(filePath);
330
+ return {
331
+ index: found.index,
332
+ width: found.width,
333
+ height: found.height,
334
+ mime: 'image/png',
335
+ base64: buffer.toString('base64'),
336
+ pageCount: cached.pages.length,
337
+ };
338
+ }
339
+ const OFFICE_DOWNLOAD_MIME = {
340
+ '.doc': 'application/msword',
341
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
342
+ '.ppt': 'application/vnd.ms-powerpoint',
343
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
344
+ };
345
+ const PDF_MANIFEST_NAME = 'pdf-manifest.json';
346
+ const CACHED_PDF_NAME = 'preview.pdf';
347
+ export function officeMimeForPath(filePath) {
348
+ return OFFICE_DOWNLOAD_MIME[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';
349
+ }
350
+ function readCachedPdfManifest(dir) {
351
+ const manifestPath = path.join(dir, PDF_MANIFEST_NAME);
352
+ if (!existsSync(manifestPath))
353
+ return null;
354
+ try {
355
+ const parsed = JSON.parse(readFileSync(manifestPath, 'utf8'));
356
+ if (!parsed || typeof parsed.pdfFile !== 'string')
357
+ return null;
358
+ const pdfPath = path.join(dir, parsed.pdfFile);
359
+ if (!existsSync(pdfPath))
360
+ return null;
361
+ return parsed;
362
+ }
363
+ catch {
364
+ return null;
365
+ }
366
+ }
367
+ /**
368
+ * 转换输入:有内嵌音视频时用剥掉媒体的副本,否则直接用原文件。
369
+ * 副本沿用原文件名,转换出来的 PDF 名字才能和原文件对得上。
370
+ */
371
+ function conversionInput(target, tmpDir) {
372
+ const stripped = stripOfficeMedia(target.realPath, tmpDir, path.basename(target.realPath));
373
+ if (!stripped)
374
+ return target.realPath;
375
+ console.log(`[office-preview] 剥离内嵌媒体 ${stripped.strippedEntries} 项,` +
376
+ `${Math.round(stripped.removedBytes / 1024 / 1024)} MiB → ${target.fileName}`);
377
+ return stripped.filePath;
378
+ }
379
+ async function renderOfficePdfUncached(target, previewDir, converter) {
380
+ const again = readCachedPdfManifest(previewDir);
381
+ if (again?.sourcePath === target.realPath && again.mtimeMs === target.mtimeMs)
382
+ return again;
383
+ mkdirSync(previewDir, { recursive: true });
384
+ const tmpDir = await mkdtemp(path.join(os.tmpdir(), 'office-pdf-'));
385
+ try {
386
+ let generatedPdf;
387
+ try {
388
+ generatedPdf = await converter.convertToPdf(conversionInput(target, tmpDir), tmpDir);
389
+ }
390
+ catch (err) {
391
+ if (err instanceof OfficeEngineMissingError) {
392
+ throw new OfficePreviewError(err.status, err.message, err.code);
393
+ }
394
+ const message = err instanceof Error ? err.message : String(err);
395
+ throw new OfficePreviewError(500, message || '排版引擎转换失败');
396
+ }
397
+ const finalPdf = path.join(previewDir, CACHED_PDF_NAME);
398
+ const stagingPdf = path.join(previewDir, `${CACHED_PDF_NAME}.tmp.${process.pid}.${Date.now()}`);
399
+ copyFileSync(generatedPdf, stagingPdf);
400
+ renameSync(stagingPdf, finalPdf);
401
+ const size = statSync(finalPdf).size;
402
+ const cached = {
403
+ sourcePath: target.realPath,
404
+ mtimeMs: target.mtimeMs,
405
+ kind: target.kind,
406
+ pdfFile: CACHED_PDF_NAME,
407
+ size,
408
+ };
409
+ writeFileSync(path.join(previewDir, PDF_MANIFEST_NAME), JSON.stringify(cached), 'utf8');
410
+ return cached;
411
+ }
412
+ finally {
413
+ await rm(tmpDir, { recursive: true, force: true });
414
+ }
415
+ }
416
+ /**
417
+ * 仅把 PPT / Word 转成 PDF 并原子缓存,不调用 pdftoppm / swiftc 切 PNG。
418
+ */
419
+ export async function ensureOfficePdfPreview(target, converter = defaultOfficeConverter) {
420
+ const previewDir = cacheDirFor(target.realPath, target.mtimeMs);
421
+ const existing = readCachedPdfManifest(previewDir);
422
+ if (existing?.sourcePath === target.realPath && existing.mtimeMs === target.mtimeMs) {
423
+ return {
424
+ fileName: target.fileName,
425
+ kind: target.kind,
426
+ path: target.realPath,
427
+ size: existing.size,
428
+ pdfFilePath: path.join(previewDir, existing.pdfFile),
429
+ };
430
+ }
431
+ let task = pdfRenderLocks.get(previewDir);
432
+ if (!task) {
433
+ task = renderOfficePdfUncached(target, previewDir, converter).finally(() => {
434
+ if (pdfRenderLocks.get(previewDir) === task)
435
+ pdfRenderLocks.delete(previewDir);
436
+ });
437
+ pdfRenderLocks.set(previewDir, task);
438
+ }
439
+ const cached = await task;
440
+ return {
441
+ fileName: target.fileName,
442
+ kind: target.kind,
443
+ path: target.realPath,
444
+ size: cached.size,
445
+ pdfFilePath: path.join(previewDir, cached.pdfFile),
446
+ };
447
+ }
448
+ /** 读取原文件(doc/docx/ppt/pptx),供浏览器直接下载。 */
449
+ export async function readOfficeFileDownload(target) {
450
+ const buffer = await readFile(target.realPath);
451
+ return {
452
+ fileName: target.fileName,
453
+ mime: OFFICE_DOWNLOAD_MIME[path.extname(target.realPath).toLowerCase()] ?? 'application/octet-stream',
454
+ size: buffer.length,
455
+ base64: buffer.toString('base64'),
456
+ };
457
+ }