跳到主要内容

腾讯文档

收藏0

腾讯文档(docs.qq.com)在线云文档操作:创建与编辑文档/表格/幻灯片/思维导图/流程图/智能表格/收集表,管理知识库空间与文件夹,读取搜索内容,文件导入导出与网页剪藏。灵栈搬运自 SkillHub tencent-docs v1.0.42。

让 AI 安装

Minsaroun最新版本 0.1.0更新于 2026-11-14下载 0 次

sidebar-pptx-generator/scripts/setup.js

12.7 KB
1#!/usr/bin/env node
2
3// setup.js - 跨平台环境检查与 slidep 安装脚本
4// 用法: node setup.js
5//
6// 环境变量:
7// WORKBUDDY_ROOT - workbuddy binaries 根目录,默认自动检测
8// NODE_PATH - 强制指定 node 路径
9// PYTHON_PATH - 强制指定 python 路径
10
11const fs = require('fs');
12const path = require('path');
13const https = require('https');
14const { spawnSync } = require('child_process');
15
16// 配置
17const SLIDEP_REGISTRY = 'https://mirrors.tencent.com/npm/';
18const SLIDEP_SCOPE = 'tencent';
19const SLIDEP_NAME = 'slidep';
20const SLIDEP_PKG_BASE = 'https://docs.gtimg.com/tgz/tencent-slidep-';
21const SLIDEP_VERSION = '3.3.0';
22
23
24// 颜色控制
25const isColorSupported = process.stdout.isTTY && process.platform !== 'win32';
26const RED = isColorSupported ? '\x1b[0;31m' : '';
27const NC = isColorSupported ? '\x1b[0m' : '';
28
29// ========== 工具函数 ==========
30
31function exec(cmd, args, options = {}) {
32 const result = spawnSync(cmd, args, {
33 encoding: 'utf8',
34 shell: process.platform === 'win32',
35 ...options,
36 });
37 return {
38 stdout: (result.stdout || '').trim(),
39 stderr: (result.stderr || '').trim(),
40 status: result.status,
41 };
42}
43
44function which(command) {
45 const cmd = process.platform === 'win32' ? 'where' : 'which';
46 const result = exec(cmd, [command], { shell: true });
47 if (result.status === 0 && result.stdout) {
48 // where 可能返回多行,取第一个
49 return result.stdout.split(/\r?\n/)[0].trim();
50 }
51 return null;
52}
53
54function existsAndExecutable(filePath) {
55 try {
56 const stats = fs.statSync(filePath);
57 if (!stats.isFile()) return false;
58 // Windows 上没有可执行权限位,只要存在 .exe / .cmd / .bat 就算可执行
59 if (process.platform === 'win32') {
60 const ext = path.extname(filePath).toLowerCase();
61 return ext === '.exe' || ext === '.cmd' || ext === '.bat' || ext === '.ps1' || ext === '';
62 }
63 // Unix: 检查 owner/group/other 的可执行位 (mode & 0o111)
64 return (stats.mode & 0o111) !== 0;
65 } catch {
66 return false;
67 }
68}
69
70function getHomeDir() {
71 return process.env.HOME || process.env.USERPROFILE || '';
72}
73
74// 获取 WorkBuddy 根目录
75function getWorkbuddyRoot() {
76 // 1. 环境变量优先级最高
77 if (process.env.WORKBUDDY_ROOT) {
78 const dir = process.env.WORKBUDDY_ROOT;
79 try {
80 if (fs.statSync(path.join(dir, 'binaries')).isDirectory()) {
81 return dir;
82 }
83 } catch { /* ignore */ }
84 }
85
86 // 2. 尝试自动检测常见位置
87 const candidates = [
88 path.join(getHomeDir(), '.workbuddy'),
89 path.join(getHomeDir(), 'WorkBuddy', '.workbuddy'),
90 process.platform === 'win32' ? 'C:\\workbuddy' : '/opt/workbuddy',
91 ];
92
93 for (const dir of candidates) {
94 try {
95 if (fs.statSync(path.join(dir, 'binaries')).isDirectory()) {
96 return dir;
97 }
98 } catch { /* ignore */ }
99 }
100
101 return null;
102}
103
104// 语义化版本排序(支持预发布标识)
105function semverCompare(a, b) {
106 const parse = (v) => {
107 const [main, pre] = v.split('-');
108 const parts = main.split('.').map(Number);
109 return { parts, pre: pre || null };
110 };
111 const av = parse(a);
112 const bv = parse(b);
113 for (let i = 0; i < Math.max(av.parts.length, bv.parts.length); i++) {
114 const ap = av.parts[i] || 0;
115 const bp = bv.parts[i] || 0;
116 if (ap !== bp) return ap - bp;
117 }
118 // 有预发布标识的版本 < 无预发布标识
119 if (av.pre && !bv.pre) return -1;
120 if (!av.pre && bv.pre) return 1;
121 if (av.pre && bv.pre) return av.pre.localeCompare(bv.pre);
122 return 0;
123}
124
125// 在目录中找最新版本文件夹
126function findLatestVersionDir(baseDir) {
127 try {
128 const entries = fs.readdirSync(baseDir);
129 const versions = entries
130 .filter((e) => /^\d+\.\d+\.\d+/.test(e))
131 .sort(semverCompare);
132 return versions.length > 0 ? versions[versions.length - 1] : null;
133 } catch {
134 return null;
135 }
136}
137
138// 查找 managed node 路径
139function findManagedNode() {
140 const wbRoot = getWorkbuddyRoot();
141 if (!wbRoot) return null;
142 const baseDir = path.join(wbRoot, 'binaries', 'node', 'versions');
143 const latest = findLatestVersionDir(baseDir);
144 if (latest) {
145 const nodePath = path.join(baseDir, latest, 'bin', process.platform === 'win32' ? 'node.exe' : 'node');
146 if (existsAndExecutable(nodePath)) return nodePath;
147 }
148 return null;
149}
150
151// 查找 managed python 路径
152function findManagedPython() {
153 const wbRoot = getWorkbuddyRoot();
154 if (!wbRoot) return null;
155 const baseDir = path.join(wbRoot, 'binaries', 'python', 'versions');
156 const latest = findLatestVersionDir(baseDir);
157 if (latest) {
158 const names = process.platform === 'win32'
159 ? ['python.exe', 'python3.exe']
160 : ['python3', 'python'];
161 for (const name of names) {
162 const pyPath = path.join(baseDir, latest, 'bin', name);
163 if (existsAndExecutable(pyPath)) return pyPath;
164 }
165 }
166 return null;
167}
168
169// 检查 node
170function checkNode() {
171 let nodePath = null;
172
173 // 优先级: 环境变量 > managed > PATH
174 if (process.env.NODE_PATH && existsAndExecutable(process.env.NODE_PATH)) {
175 nodePath = process.env.NODE_PATH;
176 } else {
177 nodePath = findManagedNode();
178 if (!nodePath) {
179 nodePath = which('node');
180 }
181 }
182
183 if (!nodePath) {
184 console.error(`${RED}✗ Node.js 未找到${NC}`);
185 console.error(' 可通过以下方式指定:');
186 if (process.platform === 'win32') {
187 console.error(' $env:NODE_PATH = "C:\\path\\to\\node.exe"');
188 } else {
189 console.error(' export NODE_PATH=/path/to/node');
190 }
191 console.error(' 或安装到 PATH 中');
192 return null;
193 }
194
195 const result = exec(nodePath, ['--version']);
196 const version = result.stdout.replace(/^v/, '');
197 console.log(`node: ${nodePath} (v${version})`);
198 return nodePath;
199}
200
201// 检查 python
202function checkPython() {
203 let pyPath = null;
204
205 // 优先级: 环境变量 > managed > PATH
206 if (process.env.PYTHON_PATH && existsAndExecutable(process.env.PYTHON_PATH)) {
207 pyPath = process.env.PYTHON_PATH;
208 } else {
209 pyPath = findManagedPython();
210 if (!pyPath) {
211 pyPath = which('python3') || which('python');
212 }
213 }
214
215 if (!pyPath) {
216 console.error(`${RED}✗ Python 未找到${NC}`);
217 console.error(' 可通过以下方式指定:');
218 if (process.platform === 'win32') {
219 console.error(' $env:PYTHON_PATH = "C:\\path\\to\\python.exe"');
220 } else {
221 console.error(' export PYTHON_PATH=/path/to/python3');
222 }
223 console.error(' 或安装到 PATH 中');
224 return null;
225 }
226
227 const result = exec(pyPath, ['--version']);
228 // Python 输出格式: "Python 3.x.y"
229 const match = result.stdout.match(/Python\s+(\S+)/);
230 const version = match ? match[1] : 'unknown';
231 console.log(`python: ${pyPath} (v${version})`);
232 return pyPath;
233}
234
235// 解析 node 对应的 npm 全局 prefix(绑定到 managed node 自己的目录)
236function getNodePrefix(nodePath) {
237 if (!nodePath) return null;
238 const dir = path.dirname(nodePath); // bin 目录或版本目录
239 const parent = path.dirname(dir); // 版本目录或 versions 目录
240 // macOS/Linux: node 在 versions/X.X.X/bin/ 下,parent 才是 prefix
241 // Windows: node.exe 直接在 versions/X.X.X/ 下,dir 就是 prefix
242 return path.basename(dir) === 'bin' ? parent : dir;
243}
244
245// 获取 slidep 二进制路径
246function getSlidepBin() {
247 let nodePath = null;
248 if (process.env.NODE_PATH && existsAndExecutable(process.env.NODE_PATH)) {
249 nodePath = process.env.NODE_PATH;
250 } else {
251 nodePath = findManagedNode();
252 }
253
254 if (nodePath) {
255 const binDir = path.dirname(nodePath);
256 const slidepName = process.platform === 'win32' ? 'slidep.cmd' : 'slidep';
257 const slidepPath = path.join(binDir, slidepName);
258 if (fs.existsSync(slidepPath)) return slidepPath;
259 // Windows 下也可能是 slidep.exe(如果它不是 cmd 包装器)
260 if (process.platform === 'win32') {
261 const slidepExe = path.join(binDir, 'slidep.exe');
262 if (fs.existsSync(slidepExe)) return slidepExe;
263 }
264 }
265
266 // 从 PATH 找
267 const fromPath = which('slidep');
268 if (fromPath) return fromPath;
269
270 return null;
271}
272
273// 获取已安装 slidep 版本
274function getInstalledSlidepVersion() {
275 const slidepBin = getSlidepBin();
276 if (!slidepBin) return null;
277 const result = exec(slidepBin, ['--version']);
278 if (result.status !== 0) return null;
279 const match = result.stdout.match(/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?)/);
280 return match ? match[1] : null;
281}
282
283// 发起 HTTPS GET 请求(Promise 包装)
284function httpsGet(url) {
285 return new Promise((resolve, reject) => {
286 https
287 .get(url, { timeout: 10000 }, (res) => {
288 if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
289 // 跟随重定向
290 httpsGet(res.headers.location).then(resolve).catch(reject);
291 return;
292 }
293 let data = '';
294 res.on('data', (chunk) => { data += chunk; });
295 res.on('end', () => resolve(data));
296 })
297 .on('error', reject)
298 .on('timeout', () => reject(new Error('Request timeout')));
299 });
300}
301
302// 获取远程最新版本
303async function getRemoteVersion() {
304 // 方法1: 通过 npm registry API 查询 scoped 包最新版本
305 try {
306 const encodedScope = `@${SLIDEP_SCOPE}%2f${SLIDEP_NAME}`;
307 const data = await httpsGet(`${SLIDEP_REGISTRY}${encodedScope}/latest`);
308 const match = data.match(/"version"\s*:\s*"(\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?)"/);
309 if (match) return match[1];
310 } catch { /* ignore */ }
311
312 // 方法2: 回退到 tgz 目录页解析
313 try {
314 const data = await httpsGet('https://docs.gtimg.com/tgz/');
315 const matches = data.match(/tencent-slidep-\d+\.\d+\.\d+\.tgz/g);
316 if (matches && matches.length > 0) {
317 // 提取版本号并排序
318 const versions = matches
319 .map((m) => m.replace(/tencent-slidep-([\d.]+)\.tgz/, '$1'))
320 .sort(semverCompare);
321 return versions[versions.length - 1];
322 }
323 } catch { /* ignore */ }
324
325 // 方法3: 兜底使用 npm view 命令
326 try {
327 const npmBin = process.platform === 'win32' ? 'npm.cmd' : 'npm';
328 const result = exec(npmBin, [
329 'view',
330 `@${SLIDEP_SCOPE}/${SLIDEP_NAME}`,
331 'version',
332 '--registry',
333 SLIDEP_REGISTRY,
334 ]);
335 if (result.status === 0 && result.stdout) {
336 const v = result.stdout.trim();
337 if (/^\d+\.\d+\.\d+/.test(v)) return v;
338 }
339 } catch { /* ignore */ }
340
341 // 最终兜底
342 return SLIDEP_VERSION;
343}
344
345// 安装/更新 slidep
346async function installSlidep() {
347 let nodePath = null;
348 if (process.env.NODE_PATH && existsAndExecutable(process.env.NODE_PATH)) {
349 nodePath = process.env.NODE_PATH;
350 } else {
351 nodePath = findManagedNode() || which('node');
352 }
353
354 if (!nodePath) {
355 console.error(`${RED}✗ 无法找到 node${NC}`);
356 process.exit(1);
357 }
358
359 const npmBin = process.platform === 'win32'
360 ? path.join(path.dirname(nodePath), 'npm.cmd')
361 : path.join(path.dirname(nodePath), 'npm');
362 const npmPrefix = getNodePrefix(nodePath);
363 const remote = await getRemoteVersion();
364 const installed = getInstalledSlidepVersion();
365
366 if (installed && installed === remote) {
367 const slidepPath = getSlidepBin();
368 console.log(`slidep: 已安装最新版 v${installed} (${slidepPath})`);
369 return;
370 }
371
372 const url = `${SLIDEP_PKG_BASE}${remote}.tgz`;
373
374 if (installed) {
375 console.log(`slidep: 升级 v${installed} → v${remote}`);
376 } else {
377 console.log(`slidep: 安装 v${remote}`);
378 }
379
380 const args = ['install', '--registry', SLIDEP_REGISTRY, '-g', url];
381 if (npmPrefix) {
382 args.push('--prefix', npmPrefix);
383 }
384
385 const result = spawnSync(npmBin, args, {
386 stdio: 'inherit',
387 shell: process.platform === 'win32',
388 });
389
390 if (result.status !== 0) {
391 console.error(`${RED}✗ npm install 失败 (exit code ${result.status})${NC}`);
392 process.exit(1);
393 }
394
395 const newVersion = getInstalledSlidepVersion();
396 const slidepPath = getSlidepBin();
397 if (newVersion === remote) {
398 console.log(`slidep: 安装成功 v${newVersion} (${slidepPath})`);
399 } else {
400 console.error(`${RED}✗ slidep 安装失败 (期望 v${remote}, 实际 v${newVersion || '未找到'})${NC}`);
401 if (slidepPath) console.error(` 当前 slidep: ${slidepPath}`);
402 process.exit(1);
403 }
404}
405
406// ========== 主流程 ==========
407
408(async () => {
409 console.log('---');
410
411 const nodePath = checkNode();
412 const pyPath = checkPython();
413
414 if (!nodePath || !pyPath) {
415 console.log('');
416 console.log('提示: 可通过环境变量指定路径');
417 if (process.platform === 'win32') {
418 console.log(' $env:NODE_PATH = "C:\\path\\to\\node.exe"');
419 console.log(' $env:PYTHON_PATH = "C:\\path\\to\\python.exe"');
420 } else {
421 console.log(' export NODE_PATH=/path/to/node');
422 console.log(' export PYTHON_PATH=/path/to/python3');
423 }
424 process.exit(1);
425 }
426
427 await installSlidep();
428
429 console.log('---');
430 console.log('✓ setup 完成');
431})();

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。