From 652920358596cdaf841702d38f79b0783363e48b Mon Sep 17 00:00:00 2001 From: margrop <1731827+margrop@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:38:15 +0800 Subject: [PATCH] =?UTF-8?q?fix(npm):=20=E4=BF=AE=E5=A4=8D=E5=90=AF?= =?UTF-8?q?=E5=8A=A8=E5=99=A8=E5=8F=82=E6=95=B0=E8=A7=A3=E6=9E=90=E3=80=81?= =?UTF-8?q?CLI=20=E5=B8=AE=E5=8A=A9=E4=B8=8E=20Node=20=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E9=A1=BA=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 用 indexOf 切分键值,`--data-dir=/tmp/a=b/data` 不再被截断;未知参数、缺值与 1-65535 外端口给出明确错误并以非零码退出。 - 任意位置出现 `-h`/`--help` 只打印帮助,`start --help` 不再启动服务;`-v`/`--version` 同理。 - Node.js 22.15 校验提前到 prepare 最前面,低版本在触碰数据库前即报错。 - prepare-client 包裹异常并显式设置 cwd 与 PRISMA_HIDE_UPDATE_MESSAGE,失败不阻断安装。 - 补充 package-launcher 单测(等号路径、参数校验、CLI 帮助与退出码),lint/tsc/语法检查通过。 Refs: https://github.com/margrop/wrong-notebook/issues/156 --- packaging/npm/bin/wrong-notebook.js | 75 +++++++++++++-------- packaging/runtime/launcher.js | 41 ++++++++--- src/__tests__/unit/package-launcher.test.ts | 60 ++++++++++++++++- 3 files changed, 137 insertions(+), 39 deletions(-) diff --git a/packaging/npm/bin/wrong-notebook.js b/packaging/npm/bin/wrong-notebook.js index 3d57507f..ef29c8db 100644 --- a/packaging/npm/bin/wrong-notebook.js +++ b/packaging/npm/bin/wrong-notebook.js @@ -26,35 +26,54 @@ const HELP = `错题本 wrong-notebook v${pkg.version} 数据库、配置文件(config/app-config.json)和会话密钥都保存在数据目录中,升级不会丢失数据。 首次启动时终端会打印一次性初始化链接,打开后设置管理员账号(链接只能使用一次)。`; -const ALIASES = { '-h': 'help', '--help': 'help', '-v': 'version', '--version': 'version' }; -const [first, ...rest] = process.argv.slice(2); -const command = ALIASES[first] || (!first || first.startsWith('-') ? 'start' : first); -const args = command === 'start' && first !== 'start' ? process.argv.slice(2) : rest; +const raw = process.argv.slice(2); +const has = (...flags) => flags.some((flag) => raw.includes(flag)); -switch (command) { - case 'start': - try { - launcher.start(launcher.parseArgs(args)); - } catch (error) { - console.error(`[wrong-notebook] 启动失败:${error.message}`); - process.exit(1); +// 任意位置出现 -h/--help 都只打印帮助,不启动服务(如 start --help、--port 8080 --help) +if (has('-h', '--help')) { + console.log(HELP); +} else if (has('-v', '--version')) { + console.log(pkg.version); +} else { + const [first, ...rest] = raw; + const command = !first || first.startsWith('-') ? 'start' : first; + const args = command === 'start' && first !== 'start' ? raw : rest; + + switch (command) { + case 'start': + try { + launcher.start(launcher.parseArgs(args)); + } catch (error) { + console.error(`[wrong-notebook] 启动失败:${error.message}`); + process.exit(1); + } + break; + case 'prepare-client': { + // 安装时生成 Prisma Client;失败不阻断安装,首次启动时会再尝试 + try { + const packageRoot = path.join(__dirname, '..'); + const cli = require.resolve('prisma/build/index.js', { paths: [packageRoot] }); + const schema = path.join(packageRoot, 'prisma', 'schema.prisma'); + const result = spawnSync(process.execPath, [cli, 'generate', '--schema', schema], { + cwd: packageRoot, + env: { ...process.env, PRISMA_HIDE_UPDATE_MESSAGE: 'true' }, + stdio: 'inherit', + }); + if (result.error) throw result.error; + if (result.status !== 0) throw new Error(`Prisma CLI 退出码 ${result.status}`); + } catch (error) { + console.warn(`[wrong-notebook] Prisma Client 生成失败,首次启动时将重试:${error.message}`); + } + break; } - break; - case 'prepare-client': { - // 安装时生成 Prisma Client;失败不阻断安装,首次启动时会再尝试 - const cli = require.resolve('prisma/build/index.js', { paths: [path.join(__dirname, '..')] }); - const schema = path.join(__dirname, '..', 'prisma', 'schema.prisma'); - const result = spawnSync(process.execPath, [cli, 'generate', '--schema', schema], { stdio: 'inherit' }); - if (result.status !== 0) console.warn('[wrong-notebook] Prisma Client 生成失败,首次启动时将重试'); - break; + case 'version': + console.log(pkg.version); + break; + case 'help': + console.log(HELP); + break; + default: + console.error(`未知命令:${command}\n\n${HELP}`); + process.exit(1); } - case 'version': - console.log(pkg.version); - break; - case 'help': - console.log(HELP); - break; - default: - console.error(`未知命令:${command}\n\n${HELP}`); - process.exit(1); } diff --git a/packaging/runtime/launcher.js b/packaging/runtime/launcher.js index 69ae9b76..417efee2 100644 --- a/packaging/runtime/launcher.js +++ b/packaging/runtime/launcher.js @@ -25,15 +25,39 @@ function parseArgs(argv) { const opts = {}; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; - const [key, inline] = arg.split('=', 2); - const next = () => (inline !== undefined ? inline : argv[++i]); - if (key === '--port' || key === '-p') opts.port = next(); - else if (key === '--host' || key === '-H') opts.host = next(); - else if (key === '--data-dir' || key === '-d') opts.dataDir = next(); + // 用 indexOf 而不是 split('=', 2):值本身可能含等号(如 --data-dir=/srv/a=b/data) + const separator = arg.indexOf('='); + const key = separator === -1 ? arg : arg.slice(0, separator); + let value = separator === -1 ? undefined : arg.slice(separator + 1); + if (key === '--port' || key === '-p' || key === '--host' || key === '-H' || key === '--data-dir' || key === '-d') { + if (value === undefined) { + if (i + 1 >= argv.length) throw new Error(`${key} 缺少参数值`); + value = argv[++i]; + } + if (!value) throw new Error(`${key} 缺少参数值`); + if (key === '--port' || key === '-p') opts.port = value; + else if (key === '--host' || key === '-H') opts.host = value; + else opts.dataDir = value; + } else { + throw new Error(`未知参数:${arg}`); + } + } + if (opts.port !== undefined) { + if (!/^\d+$/.test(opts.port) || Number(opts.port) < 1 || Number(opts.port) > 65535) { + throw new Error(`端口必须是 1-65535 的整数,当前为 ${opts.port}`); + } } return opts; } +/** 安装包依赖 Module.registerHooks(Node.js 22.15+),在任何数据库操作前先校验 */ +function assertNodeVersion() { + const Module = require('node:module'); + if (typeof Module.registerHooks !== 'function') { + throw new Error(`需要 Node.js 22.15 或更高版本(当前 ${process.version})`); + } +} + function defaultDataDir() { if (process.env.WRONG_NOTEBOOK_HOME) return process.env.WRONG_NOTEBOOK_HOME; return path.join(os.homedir(), '.wrong-notebook'); @@ -113,10 +137,8 @@ function ensurePrismaClient(env) { * 飞牛OS 打包也不接受符号链接,因此安装包不带这些链接,改为在解析失败时去掉哈希后缀再解析。 */ function installExternalAliasResolver() { + assertNodeVersion(); const Module = require('node:module'); - if (typeof Module.registerHooks !== 'function') { - throw new Error(`需要 Node.js 22.15 或更高版本(当前 ${process.version})`); - } const alias = /^((?:@[^/]+\/)?[^/]+)-[0-9a-f]{16}(\/.*)?$/; // 同时作用于 require 和 import(bcryptjs 3 为 ESM,由 import() 加载) Module.registerHooks({ @@ -147,6 +169,7 @@ function useBundledQueryEngine(env) { } function prepare(options = {}) { + assertNodeVersion(); const dataDir = path.resolve(options.dataDir || defaultDataDir()); const configDir = path.join(dataDir, 'config'); fs.mkdirSync(configDir, { recursive: true }); @@ -211,7 +234,7 @@ function start(options = {}) { require(path.join(APP_DIR, 'server.js')); } -module.exports = { prepare, start, parseArgs, defaultDataDir, sqliteUrl, ensureSecret }; +module.exports = { prepare, start, parseArgs, assertNodeVersion, defaultDataDir, sqliteUrl, ensureSecret }; if (require.main === module) { try { diff --git a/src/__tests__/unit/package-launcher.test.ts b/src/__tests__/unit/package-launcher.test.ts index 9b153029..76b47425 100644 --- a/src/__tests__/unit/package-launcher.test.ts +++ b/src/__tests__/unit/package-launcher.test.ts @@ -5,15 +5,29 @@ import fs from 'fs'; import os from 'os'; import path from 'path'; +import { spawnSync } from 'node:child_process'; import { createRequire } from 'module'; import { describe, expect, it } from 'vitest'; const require = createRequire(import.meta.url); const launcher = require('../../../packaging/runtime/launcher.js') as { parseArgs: (argv: string[]) => { port?: string; host?: string; dataDir?: string }; + assertNodeVersion: () => void; sqliteUrl: (file: string) => string; ensureSecret: (dataDir: string) => string; }; +const binSource = path.resolve(__dirname, '../../../packaging/npm/bin/wrong-notebook.js'); +const launcherSource = path.resolve(__dirname, '../../../packaging/runtime/launcher.js'); + +/** npm 发布时 bin 与 launcher.js、package.json 同在包根目录,测试按同样结构搭建临时包 */ +function makeBundleBin(): { bin: string; dir: string } { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'launcher-bin-')); + fs.mkdirSync(path.join(dir, 'bin')); + fs.copyFileSync(binSource, path.join(dir, 'bin', 'wrong-notebook.js')); + fs.copyFileSync(launcherSource, path.join(dir, 'launcher.js')); + fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'wrong-notebook', version: 'test' })); + return { bin: path.join(dir, 'bin', 'wrong-notebook.js'), dir }; +} describe('package launcher', () => { it('解析长短参数和等号写法', () => { @@ -25,8 +39,50 @@ describe('package launcher', () => { expect(launcher.parseArgs(['-p=3001', '-d', 'data'])).toEqual({ port: '3001', dataDir: 'data' }); }); - it('忽略未知参数', () => { - expect(launcher.parseArgs(['--verbose', 'start'])).toEqual({}); + it('参数值中的等号不被截断', () => { + expect(launcher.parseArgs(['--data-dir=/tmp/a=b/data'])).toEqual({ dataDir: '/tmp/a=b/data' }); + }); + + it('未知参数、缺值与非法端口给出明确错误', () => { + expect(() => launcher.parseArgs(['--verbose'])).toThrow('未知参数:--verbose'); + expect(() => launcher.parseArgs(['start'])).toThrow('未知参数:start'); + expect(() => launcher.parseArgs(['--port'])).toThrow('缺少参数值'); + expect(() => launcher.parseArgs(['--port', '0'])).toThrow('1-65535'); + expect(() => launcher.parseArgs(['--port', '70000'])).toThrow('1-65535'); + expect(() => launcher.parseArgs(['-p=abc'])).toThrow('1-65535'); + }); + + it('当前 Node 满足安装包要求', () => { + expect(() => launcher.assertNodeVersion()).not.toThrow(); + }); + + it('CLI 任意位置出现 --help 只打印帮助,不启动服务', () => { + const bundle = makeBundleBin(); + try { + for (const argv of [['start', '--help'], ['--port', '8080', '--help']]) { + const result = spawnSync(process.execPath, [bundle.bin, ...argv], { encoding: 'utf8', timeout: 5000 }); + expect(result.status, argv.join(' ')).toBe(0); + expect(result.stdout).toContain('用法:'); + expect(result.stdout).toContain('--data-dir'); + } + } finally { + fs.rmSync(bundle.dir, { recursive: true, force: true }); + } + }); + + it('CLI 对未知参数与非法端口以非零码退出', () => { + const bundle = makeBundleBin(); + try { + const unknown = spawnSync(process.execPath, [bundle.bin, 'start', '--ports', '8080'], { encoding: 'utf8', timeout: 5000 }); + expect(unknown.status).toBe(1); + expect(unknown.stderr).toContain('未知参数:--ports'); + + const badPort = spawnSync(process.execPath, [bundle.bin, 'start', '--port', '70000'], { encoding: 'utf8', timeout: 5000 }); + expect(badPort.status).toBe(1); + expect(badPort.stderr).toContain('1-65535'); + } finally { + fs.rmSync(bundle.dir, { recursive: true, force: true }); + } }); it('SQLite 地址使用正斜杠', () => {