pwish-cli 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,30 @@
1
+ # Changelog
2
+
3
+ 本项目所有重要变更均记录于此。格式遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
4
+ 版本号遵循 [Semantic Versioning](https://semver.org/lang/zh-CN/)。
5
+
6
+ ## [Unreleased]
7
+
8
+ ## [0.1.0] - 2026-11-25
9
+
10
+ 首个公开版本。
11
+
12
+ ### Added
13
+
14
+ - **本机登录页**:`pwish login` 在 `127.0.0.1` 起临时授权服务并打开自建登录页,
15
+ 支持微信扫码与手机号/邮箱 + 密码两种方式,视觉对齐佐糖官网登录页;
16
+ 登录凭据经本机服务调用官方账号接口换取登录态,密码不落盘
17
+ - OAuth 2.0 授权码 + PKCE(S256) 回环流程(state 防 CSRF、授权码一次性 60 秒、Host 校验防 DNS rebinding)
18
+ - 一句话出图 `pwish gen`:参考图上传、模型/比例/清晰度/张数/经济与稳定模式
19
+ - 电商套图 `pwish suite`:AI 按场景写提示词后批量出图(白底主图、核心卖点、卖点、材质、模特)
20
+ - 结果管理:`task`、`history`、`show`、`download`、`queue`、`quota`、`models`
21
+ - agent skill `skill/pwish/SKILL.md`
22
+ - 跨平台支持:macOS / Linux / Windows 的浏览器授权链接打开与剪贴板读取
23
+ - 工程化:静态自检、格式检查、CI(Node 20 / 22)、44+ 单元测试
24
+
25
+ ### 说明
26
+
27
+ - 套图支持 5 个场景;「场景展示图」「多场景拼图」暂不支持
28
+ - 电商详情图、电商视频暂不支持
29
+ - `--mode stable` 参数可下发,出图效果与计费差异未经实测
30
+ - 免费额度生成的图片带水印,去水印需按站点规则升级
package/LICENSE ADDED
@@ -0,0 +1,27 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pwish-cli contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ 本项目是第三方非官方工具,与佐糖 / picwish 官方无关联,也未获其授权或背书。
26
+ 使用者需自行遵守佐糖的服务条款与所在地区的法律法规;因使用本工具产生的
27
+ 账号风控、额度消耗、内容合规等后果由使用者自行承担。
package/README.md CHANGED
@@ -1,3 +1,234 @@
1
- # Temporary Holding Version
1
+ # pwish
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **佐糖 AI 设计师的官方账号登录 + 命令行出图工具。** 一句话出电商图、商品图成套出图,结果自动下载到本地。
4
+
5
+ <p>
6
+ <a href="https://www.npmjs.com/package/pwish-cli"><img alt="npm" src="https://img.shields.io/npm/v/pwish-cli?color=5555FF"></a>
7
+ <a href="https://www.npmjs.com/package/pwish-cli"><img alt="downloads" src="https://img.shields.io/npm/dm/pwish-cli"></a>
8
+ <a href="https://github.com/MisonL/pwish-cli/actions"><img alt="CI" src="https://img.shields.io/github/actions/workflow/status/MisonL/pwish-cli/ci.yml?branch=main"></a>
9
+ <img alt="node" src="https://img.shields.io/node/v/pwish-cli">
10
+ <a href="LICENSE"><img alt="license" src="https://img.shields.io/badge/license-MIT-blue"></a>
11
+ </p>
12
+
13
+ ```bash
14
+ npm i -g pwish-cli
15
+ pwish login # 本机登录页,微信扫码或账号密码
16
+ pwish gen "白底商品图,柔和影棚光" -i ./mug.jpg # 出图并自动下载
17
+ pwish suite -i ./mug.jpg --selling "白瓷马克杯 350ml" --scenes main,selling
18
+ ```
19
+
20
+ > 非官方工具:账户额度的消耗、图片水印与内容合规规则由佐糖账号与站点政策决定。
21
+
22
+ ## 目录
23
+
24
+ - [安装](#安装) · [登录](#登录) · [命令](#命令) · [例子](#例子)
25
+ - [模型](#模型) · [接口说明](#接口说明随站点更新可能变化) · [Skill](#skill)
26
+ - [开发与测试](#开发与测试) · [已知限制](#已知限制)
27
+
28
+ ## 特性
29
+
30
+ | | |
31
+ |---|---|
32
+ | **本机登录页** | 微信扫码 / 手机号邮箱密码,视觉与官网一致,凭据不落盘 |
33
+ | **一句话出图** | 支持参考图、模型、比例、清晰度、张数与经济/稳定模式 |
34
+ | **电商套图** | 商品图 → AI 写场景提示词 → 白底/卖点/材质/模特成套出图 |
35
+ | **结果管理** | 任务查询、历史会话、队列状态、过期链接重下 |
36
+ | **零依赖** | 只用 Node 内置模块,含 LevelDB/Snappy 与 PKCE 的自实现 |
37
+
38
+ ## 安装
39
+
40
+ ```bash
41
+ npm i -g pwish-cli # 从 npm 安装
42
+ # 或在仓库内:npm link
43
+ ```
44
+
45
+ 需要 Node.js ≥ 20(使用内置 `fetch`)。**无第三方运行时依赖。**
46
+
47
+ ## 开发与测试
48
+
49
+ ```bash
50
+ npm run verify # = npm run check + npm test(CI 同一套)
51
+ npm run check # 自检:语法 / 未使用 import / 硬编码凭证 / 输出层规范
52
+ npm test # node --test,46 个用例
53
+ npm run test:watch
54
+ ```
55
+
56
+ 测试覆盖:模型 payload 分族构造、套图结果解析、配置与 token 解析、参数解析、
57
+ OAuth 授权码/PKCE/CSRF/Host 防护、Snappy 解压与 varint 解码、CLI `--version`。
58
+ **测试不产生任何 API 请求、不消耗额度。** CI(`.github/workflows/ci.yml`)在 Node 20 / 22 上跑同一套。
59
+
60
+ | 文件 | 职责 |
61
+ |---|---|
62
+ | `src/api.js` | 同源接口客户端(Bearer、错误码映射、超时) |
63
+ | `src/upload.js` | OSS STS 上传(V1 签名 + `x-oss-callback` 换 resource_id) |
64
+ | `src/tasks.js` | 建会话 / 建任务 / 批量轮询 / 下载 / 历史 / 队列 |
65
+ | `src/suite.js` | 电商套图两步流程(AI 写提示词 → 批量出图) |
66
+ | `src/models.js` | **模型表、比例尺寸表、场景表、payload 构造(改版时的主要改点)** |
67
+ | `src/auth-server.js` | 本机授权服务:登录页 + OAuth 授权码 + PKCE |
68
+ | `src/passport.js` | 官方账号登录接口客户端(扫码 / 密码) |
69
+ | `src/login-page.js` | 自建登录页与结果页(对齐官网视觉) |
70
+ | `src/browser-token.js` | 只读解析 Chromium localStorage(LevelDB + Snappy) |
71
+ | `src/args.js` / `src/output.js` | 参数解析 / 输出与着色(stdout/stderr 分离) |
72
+ | `src/cli.js` | 命令路由与业务编排 |
73
+ | `scripts/check.js` | 零依赖静态自检 |
74
+ | `test/` | 单元与 CLI 冒烟测试 |
75
+
76
+ 版本与变更记录见 `CHANGELOG.md`;许可证见 `LICENSE`(MIT + 非官方工具免责声明)。
77
+
78
+ ## 登录
79
+
80
+ ```bash
81
+ pwish login
82
+ ```
83
+
84
+ 命令会在本机 `127.0.0.1` 启动一个**自建登录页**并自动打开浏览器:
85
+
86
+ - **微信扫码**:页面直接展示官方生成的二维码,手机上确认即可;
87
+ - **密码登录**:手机号或邮箱 + 密码。
88
+
89
+ 登录凭据只交给本机服务,由它调用官方账号接口换取登录态,密码不保存、不外传。
90
+ 拿到登录态后页面提示「授权完成」,终端自动继续。
91
+
92
+ ### 为什么是本机页面
93
+
94
+ 网页端的登录态只能由官方接口签发。为了让 CLI 也能正当地登录,本机起了一个临时授权服务,
95
+ 页面视觉与佐糖官网登录页一致(品牌紫蓝渐变、白卡片、相同输入框规格),
96
+ 底层复用官方登录接口,不接触任何第三方:
97
+
98
+ 1. `pwish login` 起服务,生成 `state` 与 PKCE(S256) 参数,打开授权页;
99
+ 2. 用户在页面上登录 → 本机服务调用官方接口换取 `api_token`;
100
+ 3. 服务签发一次性授权码(60 秒、单次使用),页面跳回 `/callback`;
101
+ 4. CLI 校验 `state` 与 PKCE 后收下 token,写入配置。
102
+
103
+ ### 其他入口
104
+
105
+ | 命令 | 场景 |
106
+ |---|---|
107
+ | `pwish login --no-open` | 不自动开浏览器,只打印授权链接(远程/SSH) |
108
+ | `pwish login --port 8765` | 指定回环端口(默认随机) |
109
+ | `pwish login --token 'v2,...'` | CI / 无浏览器环境直接给 token |
110
+ | `pwish login --paste` | 从剪贴板读 token |
111
+ | `pwish whoami` / `pwish quota` / `pwish logout` | 账号 / 额度 / 退出 |
112
+
113
+ 安全设计:
114
+ - 只 `listen` 在 `127.0.0.1`,校验 `Host` 头,防 DNS rebinding;
115
+ - `state` 防 CSRF 且一次性;PKCE S256 把授权码绑死在本客户端;
116
+ - 授权码一次性、60 秒过期;token 只经 POST body 与内存传递,不进 URL、不进日志;
117
+ - 密码只在一次请求中透传给官方接口,不落盘;
118
+ - 凭证存 `~/.config/pwish/config.json`,权限 `0600`。
119
+
120
+ 环境变量:
121
+
122
+ | 变量 | 作用 |
123
+ |---|---|
124
+ | `PWISH_TOKEN` | 临时覆盖 token |
125
+ | `PWISH_OUT` | 默认输出目录 |
126
+ | `PWISH_API_BASE` | 覆盖接口域名(默认 `https://aw.aoscdn.com/app/picwish`) |
127
+ | `PWISH_PASSPORT_BASE` | 覆盖账号登录接口域名 |
128
+ | `PWISH_CONFIG_DIR` | 覆盖配置目录 |
129
+ | `PWISH_DEBUG` | 出错时打印原始响应/堆栈 |
130
+
131
+ ## 命令
132
+
133
+ ```bash
134
+ pwish whoami # 当前账号
135
+ pwish quota # 免费额度(按模型)
136
+ pwish models # 模型 / 比例 / 清晰度表
137
+
138
+ pwish gen "提示词" -i 参考图 [-m 模型] [-r 比例] [-s 2K] [--mode economy|stable] [-n 张数] [-o 目录]
139
+ pwish suite -i 商品图 [--selling "卖点"] [--site amazon] [--scenes main,core,selling,material,person]
140
+
141
+ pwish history [--limit 20]
142
+ pwish show <conversation_id>
143
+ pwish task <task_id> [...]
144
+ pwish download <task_id|conversation_id> [-o 目录]
145
+ pwish queue
146
+ ```
147
+
148
+ 全局开关:`--json`(机器可读)、`-o/--out`(输出目录,默认 `out/`)、`--version`(版本号)。
149
+
150
+ `--mode` 支持 `economy`(默认)与 `stable`;**`stable` 参数会正确下发但尚未实测**出图效果与计费差异。
151
+
152
+ ## 例子
153
+
154
+ ```bash
155
+ # 白底主图
156
+ pwish gen "纯白色背景,商品居中占画面85%,柔和影棚光,高细节" -i ./mug.jpg -m gpt-image-2 -r 1:1 -s 2K
157
+
158
+ # 电商套图:亚马逊,5 个可用场景里的 3 个
159
+ pwish suite -i ./mug.jpg --selling "简约白瓷马克杯 350ml,可微波加热" \
160
+ --site amazon --scenes main,selling,material
161
+
162
+ # 一次出 3 张备选
163
+ pwish gen "白底商品图,柔和阴影" -i ./mug.jpg -n 3 -o out/v1
164
+ ```
165
+
166
+ ## 模型
167
+
168
+ | key | id | 说明 |
169
+ |---|---|---|
170
+ | `gemini-3` | 6 | 电商模型 3.0(最强,10-20 算粒/张) |
171
+ | `nano-banana-pro` | 72 | 电商模型 2.0 |
172
+ | `nano-banana-2-lite` | 61 | 电商模型 1.0(最便宜) |
173
+ | `gpt-image-2` | 195 | GPT Image 2(补贴通用模型,3-5 算粒/张) |
174
+ | `gpt-image-2-flare` | 89 | GPT Image 2 Flare |
175
+ | `gpt-image-1.5` | 190 | GPT Image 1.5 |
176
+ | `gpt-image-1` | 83 | GPT Image 1 |
177
+ | `gemini-2.5` | 154 | Gemini 2.5 Flash Image |
178
+ | `seedream-5-pro` / `-flash` / `5.5` | 78 / 79 / 94 | Seedream 系列 |
179
+ | `jimeng-4.5` | 41 | 即梦 4.5 |
180
+ | `flux` | 1 | FLUX |
181
+
182
+ 比例:`auto 1:1 2:3 3:2 3:4 4:3 9:16 16:9`;清晰度:`1K 2K 2K+`(→ standard/high/super)。
183
+
184
+ ### 场景(`--scenes`)
185
+
186
+ 电商套图支持 5 个场景,均已实测:`main`(白底主图) `core`(核心卖点图) `selling`(卖点图) `material`(材质图) `person`(模特展示图)。
187
+ 站点 UI 还有「场景展示图」「多场景拼图」两个选项,其接口参数尚未确认,CLI 暂不支持。
188
+
189
+ ## 接口说明(随站点更新可能变化)
190
+
191
+ 基址 `https://aw.aoscdn.com/app/picwish`,`Authorization: Bearer <passport_api_token>`,
192
+ 所有请求带 `product_id=482&language=zh`。
193
+
194
+ | 用途 | 接口 |
195
+ |---|---|
196
+ | 额度 | `GET vips/all-free-counts` |
197
+ | 建会话 | `POST image/conversations` |
198
+ | 一句话出图 | `POST tasks/login/image-messages` |
199
+ | 批量查任务 | `GET tasks/login/image-messages/batch?task_ids=` |
200
+ | 队列 | `GET image/conversations/task-queue` |
201
+ | 会话列表/详情 | `GET image/conversations`、`GET image/conversations/{id}` |
202
+ | 套图:AI 写提示词 | `POST tasks/login/suite/prompt` → `GET tasks/login/suite/prompt/{task_id}` |
203
+ | 套图:出图 | `POST tasks/login/suite` → `GET tasks/login/suite/{task_id}` |
204
+ | 上传授权 | `POST authorizations/oss`(STS,随后 PUT 到 OSS 带 `x-oss-callback` 换 `resource_id`) |
205
+
206
+ 生成结果轮询到 `state=1`(或 `progress=100`)后,`answer[].file` 即图片 URL(OSS 签名约 2 小时有效)。
207
+
208
+ ## Skill
209
+
210
+ `skill/pwish/SKILL.md` 是为 agent 准备的用法协议(额度预检、模型选择、套图配方、错误码处理、提示词方法论)。
211
+ 安装到 agent 技能目录即可:
212
+
213
+ ```bash
214
+ cp -R skill/pwish ~/.agents/skills/pwish
215
+ ```
216
+
217
+ ## 已知限制
218
+
219
+ **能力边界**(没做 / 没验证,不要当成能用):
220
+
221
+ - **详情图(电商详情图)未实现**:站点有该功能,CLI 尚未支持,无对应命令。
222
+ - **视频生成未实现**:接口存在(`tasks/login/video-messages`),未验证也未封装。
223
+ - **套图场景 5/7**:见上文「场景」,「场景展示图」「多场景拼图」不支持。
224
+ - **`--mode stable` 未实测**:参数正确下发,但只验证过 `economy`。
225
+ - **浏览器直读仅限 Chromium 系**:Chrome / Edge / Brave / Chromium / Arc / Vivaldi 可用;
226
+ **Safari 与 Firefox 不支持**,会自动回退到网页 OAuth。
227
+ - **上传单文件上限 20MB**(CLI 侧保护)。实际站点限制未逐一验证。
228
+
229
+ **产品与环境限制**:
230
+
231
+ - 免费额度生成的图片**带水印**(URL/文件名含 `-wm_`);去水印需按站点规则付费。
232
+ - 结果图片 URL 是签名链接(约 2 小时),过期需用 `pwish download` 重新拉(会自动重新查询拿新签名)。
233
+ - 接口无公开文档,字段以实测为准;站点改版可能导致失效,`src/models.js` 是模型/比例/场景的单一改点。
234
+ - 读取浏览器 localStorage 依赖磁盘布局,Chromium 大版本改动格式时可能失效(届时回退 OAuth)。
package/VERSIONING.md ADDED
@@ -0,0 +1,33 @@
1
+ # 版本与发布管理
2
+
3
+ ## 版本格式
4
+
5
+ 遵循 [Semantic Versioning 2.0.0](https://semver.org/lang/zh-CN/):`MAJOR.MINOR.PATCH`。
6
+
7
+ | 变化类型 | 规则 | 例子 |
8
+ |---|---|---|
9
+ | PATCH | 向后兼容的 bug 修复 | 0.2.0 → 0.2.1 |
10
+ | MINOR | 向后兼容的新功能 | 0.2.0 → 0.3.0 |
11
+ | MAJOR | 不兼容的 API/行为变更 | 0.2.0 → 1.0.0 |
12
+
13
+ 当前阶段所有版本均 < 1.0.0,表示接口非官方、可能随站点变化。
14
+
15
+ ## 发布流程
16
+
17
+ 1. **改代码**,确保 `npm run verify` 全绿(自检 + 格式 + 44 测试)。
18
+ 2. **更新 CHANGELOG.md**:把改动写入 `[Unreleased]` 之上的新版本段落,标注日期。
19
+ 3. **升版本号**:`npm version patch|minor|major`(会自动改 package.json 并打 git tag `vX.Y.Z`)。
20
+ 4. **同步 skill 安装副本**(如本地有):`cp -R skill/pwish ~/.agents/skills/pwish`。
21
+ 5. **推送**:`git push && git push --tags`。
22
+ 6. **发布**:`npm publish`(`prepublishOnly` 会自动再跑一遍 verify)。
23
+
24
+ ## 禁止事项
25
+
26
+ - 不要把 token、用户 ID、本机绝对路径(`/Users/...`、`C:\Users\...`)写进代码、测试或文档。
27
+ 测试用例里的 token 必须是明显占位符(如 `v2,10000001,482,deadbeef`)。
28
+ - 不要在文档里描述接口获取方式的实现细节。
29
+ - 不要跳过 `verify`;CI(Node 20 / 22)会重复该检查。
30
+
31
+ ## 已发布版本
32
+
33
+ 见 CHANGELOG.md 或 `npm view pwish-cli versions`。
package/bin/pwish.js ADDED
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../src/cli.js";
3
+ import { UserError } from "../src/config.js";
4
+ import { ApiError } from "../src/api.js";
5
+
6
+ try {
7
+ const code = await main(process.argv.slice(2));
8
+ process.exitCode = code ?? 0;
9
+ } catch (err) {
10
+ if (err instanceof UserError) {
11
+ process.stderr.write(`\u001b[31m✗ ${err.message}\u001b[0m\n`);
12
+ if (err.hint) process.stderr.write(`${err.hint}\n`);
13
+ process.exitCode = 2;
14
+ } else if (err instanceof ApiError) {
15
+ process.stderr.write(`\u001b[31m✗ ${err.message}\u001b[0m\n`);
16
+ if (process.env.PWISH_DEBUG) process.stderr.write(`${JSON.stringify(err.payload, null, 2)}\n`);
17
+ process.exitCode = err.code === "UNAUTHORIZED" || err.code === "NO_TOKEN" ? 3 : 1;
18
+ } else {
19
+ process.stderr.write(`\u001b[31m✗ ${err?.message || err}\u001b[0m\n`);
20
+ if (process.env.PWISH_DEBUG) process.stderr.write(`${err?.stack}\n`);
21
+ process.exitCode = 1;
22
+ }
23
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "pwish-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "佐糖 AI 设计师(picwish.cn)命令行工具:一句话出电商图、商品图成套出图,自动下载结果",
5
+ "type": "module",
6
+ "bin": {
7
+ "pwish": "bin/pwish.js"
8
+ },
9
+ "engines": {
10
+ "node": ">=20"
11
+ },
12
+ "files": [
13
+ "bin",
14
+ "src",
15
+ "scripts",
16
+ "skill",
17
+ "README.md",
18
+ "LICENSE",
19
+ "CHANGELOG.md",
20
+ "VERSIONING.md"
21
+ ],
22
+ "scripts": {
23
+ "test": "node --test \"test/*.test.js\"",
24
+ "test:watch": "node --test --watch \"test/*.test.js\"",
25
+ "check": "node scripts/check.js",
26
+ "verify": "npm run check && npm run format:check && npm test",
27
+ "prepublishOnly": "npm run verify",
28
+ "format:check": "node scripts/format-check.js"
29
+ },
30
+ "license": "MIT",
31
+ "keywords": [
32
+ "cli",
33
+ "picwish",
34
+ "ecommerce",
35
+ "image-generation",
36
+ "ai-designer",
37
+ "电商图",
38
+ "佐糖"
39
+ ],
40
+ "author": "pwish-cli contributors",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/MisonL/pwish-cli.git"
44
+ },
45
+ "homepage": "https://github.com/MisonL/pwish-cli#readme",
46
+ "bugs": {
47
+ "url": "https://github.com/MisonL/pwish-cli/issues"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 零依赖自检:语法、未使用 import、硬编码凭证、stdout/stderr 卫生。
4
+ * 用法:node scripts/check.js
5
+ */
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { execFileSync } from "node:child_process";
10
+
11
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
12
+ const SRC_DIRS = ["src", "bin", "scripts"];
13
+ const problems = [];
14
+
15
+ function walk(dir) {
16
+ const out = [];
17
+ for (const entry of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) {
18
+ const rel = path.join(dir, entry.name);
19
+ if (entry.isDirectory()) out.push(...walk(rel));
20
+ else if (entry.name.endsWith(".js")) out.push(rel);
21
+ }
22
+ return out;
23
+ }
24
+
25
+ const files = SRC_DIRS.flatMap((d) => (fs.existsSync(path.join(ROOT, d)) ? walk(d) : []));
26
+
27
+ for (const file of files) {
28
+ const abs = path.join(ROOT, file);
29
+ const source = fs.readFileSync(abs, "utf8");
30
+
31
+ // 1. 语法
32
+ try {
33
+ execFileSync(process.execPath, ["--check", abs], { stdio: "pipe" });
34
+ } catch (err) {
35
+ problems.push(`${file}: 语法错误\n${err.stderr?.toString().split("\n")[0] ?? err.message}`);
36
+ continue;
37
+ }
38
+
39
+ // 2. 未使用的 import
40
+ const importRe = /import\s+(?:\{([^}]*)\}|(\w+))\s+from\s+["'][^"']+["']/g;
41
+ for (const m of source.matchAll(importRe)) {
42
+ const names = m[1]
43
+ ? m[1].split(",").map((n) => n.trim().split(/\s+as\s+/).pop()).filter(Boolean)
44
+ : [m[2]];
45
+ const rest = source.slice(m.index + m[0].length);
46
+ for (const name of names) {
47
+ if (!new RegExp(`\\b${name}\\b`).test(rest)) problems.push(`${file}: 未使用的 import 「${name}」`);
48
+ }
49
+ }
50
+
51
+ // 3. 硬编码凭证(v2,<uid>,<pid>,<hex>)
52
+ const secret = source.match(/v2,\d{5,},\d+,[0-9a-f]{16,}/);
53
+ if (secret) problems.push(`${file}: 疑似硬编码 token「${secret[0].slice(0, 12)}…」`);
54
+
55
+ // 4. 直接用 console.* 而非 output 层(脚本与 bin 除外)
56
+ if (file.startsWith("src/") && file !== "src/output.js") {
57
+ if (/\bconsole\.(log|info)\b/.test(source)) problems.push(`${file}: 请用 output.js 而非 console.log`);
58
+ }
59
+
60
+ // 5. FIXME/XXX 遗留(跳过自检脚本自身,它包含这些字面量)
61
+ if (file !== "scripts/check.js") {
62
+ const marker = source.match(/\b(FIXME|XXX)\b/);
63
+ if (marker) problems.push(`${file}: 遗留 ${marker[1]}`);
64
+ }
65
+ }
66
+
67
+ if (problems.length) {
68
+ console.error(`✗ 自检失败(${problems.length} 项)`);
69
+ for (const p of problems) console.error(` - ${p}`);
70
+ process.exit(1);
71
+ }
72
+ console.log(`✓ 自检通过(${files.length} 个文件)`);
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ /** 零依赖格式检查:缩进、行尾空白、末尾换行、行宽提醒。 */
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
8
+ const problems = [];
9
+
10
+ function walk(dir, exts) {
11
+ const out = [];
12
+ for (const e of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) {
13
+ if (e.name === "node_modules" || e.name === ".git") continue;
14
+ const rel = path.join(dir, e.name);
15
+ if (e.isDirectory()) out.push(...walk(rel, exts));
16
+ else if (exts.some((x) => e.name.endsWith(x))) out.push(rel);
17
+ }
18
+ return out;
19
+ }
20
+
21
+ const files = ["src", "bin", "test", "scripts"].flatMap((d) => {
22
+ const dir = path.join(ROOT, d);
23
+ return fs.existsSync(dir) ? walk(d, [".js"]) : [];
24
+ });
25
+ files.push("package.json", "README.md", "CHANGELOG.md", "LICENSE");
26
+
27
+ for (const file of files) {
28
+ const abs = path.join(ROOT, file);
29
+ const text = fs.readFileSync(abs, "utf8");
30
+ const lines = text.split("\n");
31
+
32
+ if (text.includes("\r\n")) problems.push(`${file}: 含 CRLF 行尾,应为 LF`);
33
+ if (!text.endsWith("\n")) problems.push(`${file}: 缺少末尾换行`);
34
+ for (let i = 0; i < lines.length; i++) {
35
+ if (/\s+$/.test(lines[i]) && i < lines.length - 1) problems.push(`${file}:${i + 1}: 行尾空白`);
36
+ if (/^\t/.test(lines[i])) problems.push(`${file}:${i + 1}: 缩进应为空格而非 tab`);
37
+ }
38
+ }
39
+
40
+ if (problems.length) {
41
+ console.error(`✗ 格式检查失败(${problems.length} 项)`);
42
+ problems.slice(0, 40).forEach((p) => console.error(` - ${p}`));
43
+ if (problems.length > 40) console.error(` ... 另有 ${problems.length - 40} 项`);
44
+ process.exit(1);
45
+ }
46
+ console.log(`✓ 格式检查通过(${files.length} 个文件)`);