@aronnaxlin/bgm-cli 1.1.5 → 1.1.7
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/package.json +1 -1
- package/skills/bgm-cli-develop/SKILL.md +30 -352
- package/skills/bgm-cli-operate/SKILL.md +38 -239
- package/src/commands/search.js +66 -9
- package/src/utils/validators.js +17 -0
package/package.json
CHANGED
|
@@ -1,371 +1,49 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: "bgm-cli-develop"
|
|
3
|
-
description: "Use when
|
|
3
|
+
description: "Use when contributing to or modifying the bgm-cli codebase: code conventions, architecture mapping, testing requirements, release workflows, and Bangumi domain quirks."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# bgm-cli Develop
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
Guidance for developing and maintaining the `bgm-cli` repository.
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
## Architecture and File Ownership
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
Follow the three-tier structure:
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
- API transport (`src/core/client.js`, `src/core/http.js`): Bangumi REST client, request transport, error normalization.
|
|
15
|
+
- Configuration and formatting (`src/core/config.js`, `src/core/output.js`): Config persistence, JSON passthrough, table and human rendering. Non-API strings must be English only.
|
|
16
|
+
- Command routing (`src/cli.js`, `src/commands/*.js`): CLI argument parsing, subcommands, and high-level workflows.
|
|
15
17
|
|
|
16
|
-
-
|
|
17
|
-
- file ownership and entrypoint mapping
|
|
18
|
-
- implementation conventions and change boundaries
|
|
19
|
-
- auth, collection, and output behavior that should be preserved
|
|
20
|
-
- lightweight default verification for code and docs changes
|
|
18
|
+
For self-hosted backend code, see `oauth-backend/src/`. Installation scripts live under `scripts/`.
|
|
21
19
|
|
|
22
|
-
##
|
|
20
|
+
## Key Conventions and Domain Quirks
|
|
23
21
|
|
|
24
|
-
`bgm
|
|
22
|
+
- Command style: Use positional subcommands for actions (e.g., `bgm calendar all`, not `--all`). Flags are reserved for options (e.g., `--limit 5`).
|
|
23
|
+
- Arg parsing in `main()`: Flag tokens can occupy the `command` slot if placed immediately after the group. Merge `--` prefixed `command` arguments back into `args` when checking flags.
|
|
24
|
+
- Dual-channel auth:
|
|
25
|
+
- Official web session (`p1` cookie) takes precedence.
|
|
26
|
+
- Personal Access Token acts as fallback.
|
|
27
|
+
- Never double-send session cookies and Access Tokens on `p1` requests.
|
|
28
|
+
- Episode vs. book progress:
|
|
29
|
+
- Anime/game/real uses dedicated episode endpoints.
|
|
30
|
+
- Books use `book` commands (`ep_status` / `vol_status`).
|
|
31
|
+
- Both require the subject to exist in the user's collection before updating progress.
|
|
32
|
+
- Link resolution: Maintained in `src/utils/bangumi-url.js`. Keep host handling and fragment routing aligned with web URL structures.
|
|
25
33
|
|
|
26
|
-
|
|
34
|
+
## Verification Checklist
|
|
27
35
|
|
|
28
|
-
|
|
29
|
-
- user profile reads
|
|
30
|
-
- subject search and subject reads
|
|
31
|
-
- episode list plus episode-progress status and watch writes
|
|
32
|
-
- book progress reads and writes (`book get`, `book ep`, `book vol`) for book-type subjects
|
|
33
|
-
- collection list, get, comment, rate, and status changes
|
|
34
|
-
- subject discussion topic/post CRUD plus topic and collection reaction writes
|
|
35
|
-
- episode comments plus episode-progress writes
|
|
36
|
-
- character/person comments plus photo preview/detail/comment reads
|
|
37
|
-
- group reads plus topic/post CRUD and selected Turnstile-gated group writes
|
|
38
|
-
- blog reads plus experimental Turnstile-gated blog comment writes
|
|
39
|
-
- index reads and writes (create, update, delete, comments, related items)
|
|
40
|
-
- timeline reads, SSE event sampling, and Turnstile-gated timeline `say` and `reply`
|
|
41
|
-
- weekly anime broadcast calendar (`calendar today`, `calendar all`, `calendar <weekday>`)
|
|
42
|
-
- machine-readable output with `--json`
|
|
43
|
-
- optional self-hosted `oauth-backend` for hosted OAuth and official-first Turnstile relay flows
|
|
36
|
+
Run checks and test suite before submitting changes:
|
|
44
37
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
1. `README.md`
|
|
52
|
-
2. `SKILLS.md`
|
|
53
|
-
3. this skill
|
|
54
|
-
|
|
55
|
-
## Ownership Map
|
|
56
|
-
|
|
57
|
-
Main files and directories:
|
|
58
|
-
|
|
59
|
-
- `src/cli.js`: command parsing, command handlers, init flow, ordinary CLI and TUI entrypoints
|
|
60
|
-
- `src/core/client.js`: Bangumi API client, OAuth client, hosted backend client
|
|
61
|
-
- `src/core/http.js`: request transport and error normalization
|
|
62
|
-
- `src/core/config.js`: config defaults, merge behavior, runtime persistence, install mode
|
|
63
|
-
- `src/core/output.js`: human-readable rendering and JSON output path
|
|
64
|
-
- `oauth-backend/src/*`: optional hosted OAuth backend
|
|
65
|
-
- `scripts/*`: installation helpers
|
|
66
|
-
- `skills/*`: published installable skill packages
|
|
67
|
-
- `docs/*`: repository docs and research notes
|
|
68
|
-
|
|
69
|
-
Search these command handlers first before making CLI changes:
|
|
70
|
-
|
|
71
|
-
- `runConfigCommand`
|
|
72
|
-
- `runAuthCommand`
|
|
73
|
-
- `runSetupCommand`
|
|
74
|
-
- `runSubjectCommand`
|
|
75
|
-
- `runEpisodeCommand`
|
|
76
|
-
- `runBookCommand`
|
|
77
|
-
- `runGroupCommand`
|
|
78
|
-
- `runUserCommand`
|
|
79
|
-
- `runCollectionCommand`
|
|
80
|
-
- `runCalendarCommand`
|
|
81
|
-
- `runIndexCommand`
|
|
82
|
-
|
|
83
|
-
## Core Principles
|
|
84
|
-
|
|
85
|
-
- prefer the smallest correct change
|
|
86
|
-
- preserve existing command semantics unless the task explicitly requires a behavior change
|
|
87
|
-
- keep automation and verification non-interactive by default
|
|
88
|
-
- prefer source-owned fixes in the right layer over duplicated command-local patches
|
|
89
|
-
- do not introduce new complexity when an existing helper already covers the behavior
|
|
90
|
-
|
|
91
|
-
## Working Defaults
|
|
92
|
-
|
|
93
|
-
- treat the ordinary CLI command path as the default engineering surface
|
|
94
|
-
- do not start from `bgm tui` unless the task explicitly requires TUI behavior
|
|
95
|
-
- prefer the narrowest change in the owning module instead of adding parallel abstractions
|
|
96
|
-
- reuse existing client and helper functions before adding new command-local logic
|
|
97
|
-
- if output behavior changes, update both the command implementation and `src/core/output.js`
|
|
98
|
-
|
|
99
|
-
## Domain Conventions
|
|
100
|
-
|
|
101
|
-
### Bangumi comments and reactions
|
|
102
|
-
|
|
103
|
-
- Bangumi comment bodies can contain `(bgmNN)` emote codes, and the site renders them as inline emojis.
|
|
104
|
-
- Reaction-style `like` commands are target-specific; do not assume every sticker code works everywhere.
|
|
105
|
-
- Keep a copy of the full emote mapping around for AI output and comment generation, but maintain a narrower per-target reaction allow-list for write validation.
|
|
106
|
-
|
|
107
|
-
### Auth
|
|
108
|
-
|
|
109
|
-
- `bgm --init` and `bgm auth login` are the recommended official login path
|
|
110
|
-
- Access Token remains a preserved second channel for compatibility and scripting
|
|
111
|
-
- CLI OAuth helper flows are supported but secondary
|
|
112
|
-
- hosted `oauth-backend` is experimental and should only be expanded deliberately
|
|
113
|
-
- if an auth task is ambiguous, preserve the two-channel contract: official p1 login/session first, Access Token second, and no credential double-send on p1 requests
|
|
114
|
-
|
|
115
|
-
**Turnstile / Hosted Backend Quirks**
|
|
116
|
-
|
|
117
|
-
- `startHostedRelayReceiver()` lives in `src/utils/auth-flow.js` and currently binds/exposes `http://127.0.0.1:<port>/callback` so browser fetches from the hosted callback page can reach the local CLI relay.
|
|
118
|
-
- Do not change that relay URL back to `0.0.0.0`; it can be useful as a listen address but is not a browser-fetchable callback target.
|
|
119
|
-
- `oauth-backend/src/app.js` `normalizeRelayUrl()` currently accepts valid `http:` and `https:` URLs; it does not contain a localhost-only allow-list.
|
|
120
|
-
- The hosted backend API endpoint is `POST /api/turnstile/session` with body field `relay_url` (or `relayUrl` as fallback). It returns `{"error":"missing_relay_url"}` when the relay URL is absent or invalid.
|
|
121
|
-
- Remote/VPS Turnstile operation needs a deliberately designed public relay URL and backend policy; do not patch localhost behavior casually or hardcode public IPs.
|
|
122
|
-
|
|
123
|
-
### Collections
|
|
124
|
-
|
|
125
|
-
- preserve current Bangumi-specific constraints unless they are explicitly revalidated
|
|
126
|
-
- prefer explicit `subject_id` or `--pick` aware flows for deterministic behavior
|
|
127
|
-
- keep post-write verification when changing rating, status, or collect behavior
|
|
128
|
-
- when adding collection filtering or sorting behavior, update both normalization and the actual sorter
|
|
129
|
-
|
|
130
|
-
**Resolved gaps (v0.1.3 → current):**
|
|
131
|
-
|
|
132
|
-
The following were addressed in commits `c893e25` through `aaac995`:
|
|
133
|
-
|
|
134
|
-
1. ✅ **`--offset` is now implemented in `executeCollectionListCommand`.** The CLI parses and forwards the `--offset` flag to the Bangumi API's native offset parameter. (c893e25)
|
|
135
|
-
|
|
136
|
-
2. ✅ **Single-value filters (`subject_type`, `type`) are passed to the Bangumi API** to reduce payload size. `fetchAllCollections` accepts an optional `{ query }` parameter; when a single subject type or collection status is specified, it's forwarded as a query param. Multi-value filters still fall back to client-side filtering. (c893e25)
|
|
137
|
-
|
|
138
|
-
3. ✅ **Parallel fetch with bounded concurrency (8 requests/batch).** `fetchAllCollections` uses `Promise.all` in batches of 8. Also applied to `fetchAllSubjects` for auto-paginated subject list queries. (c893e25, ac041b4)
|
|
139
|
-
|
|
140
|
-
4. ✅ **401 errors now include auto-generated hints** suggesting `bgm auth refresh --save` or `bgm auth set-token <access_token>`. (c893e25)
|
|
141
|
-
|
|
142
|
-
5. ✅ **CJK-safe table formatting.** All list commands (`collection list`, `subject list`, `group list/topics/members`, `blog list`) now render as `│`-delimited tables with proper CJK character width handling (Chinese/Japanese counted as 2 columns). Uses `formatTable()` with `displayWidth()`/`truncateDisplay()` helpers. (1f4e05e)
|
|
143
|
-
|
|
144
|
-
6. ✅ **`subject list` auto-paginates when `limit > 100`.** The Bangumi v0 API enforces limit ≤ 100. `fetchAllSubjects()` with bounded concurrency fetches additional pages transparently. (ac041b4)
|
|
145
|
-
|
|
146
|
-
7. ✅ **`subject get --verbose`** adds tags with counts and rating distribution to output. Bar charts (`█` characters) removed from verbose output for cleaner display. (4329ee8, 506613e)
|
|
147
|
-
|
|
148
|
-
8. ✅ **`collection list --sort user_score` outputs sorted correctly.** API filter passthrough reduces payload size enough that client-side sort overhead is negligible.
|
|
149
|
-
|
|
150
|
-
**Still open:**
|
|
151
|
-
|
|
152
|
-
- ❌ **No progress indication when fetching large collections/subject lists.** `fetchAllCollections` and `fetchAllSubjects` paginate silently with no user feedback. For users with 1000+ items, the CLI appears to hang for several seconds.
|
|
153
|
-
- ❌ **No early termination for `--limit`.** `fetchAllCollections` always fetches ALL pages before applying `--limit` slicing in memory. Tested with user `asm13177806` (UID 78670, 223,623 collections): even `--limit 1` tries to fetch all 2,236 pages across 280 batches, timing out after 120s+. The limit should short-circuit the fetch loop once enough items are collected, OR the offset/limit should be passed directly to the API for server-side pagination (which the v0 API does support). Combined with the silent pagination issue, this makes the CLI effectively unusable for whale accounts.
|
|
154
|
-
- ❌ **Sort remains in-memory** — Bangumi v0 API provides no server-side sort parameter for collections. Mitigated by API filter passthrough keeping payloads small.
|
|
155
|
-
- ❌ **Node.js version warning.** Package requires `>=20` but works on v18.19.1 with `EBADENGINE` warnings from npm.
|
|
156
|
-
- ✅ **Version metadata stays in sync.** The version lives in git tags only; `bgm --version`, the default User-Agent and the config default `appVersion` all read `package.json` through `src/utils/version.js`. Never hardcode a version string.
|
|
157
|
-
|
|
158
|
-
Relevant helpers in `src/cli.js`:
|
|
159
|
-
|
|
160
|
-
- `resolveCollectionTarget`
|
|
161
|
-
- `selectSubjectFromSearch`
|
|
162
|
-
- `buildCollectionMutationPayload`
|
|
163
|
-
- `fetchMySubjectCollection`
|
|
164
|
-
- `fetchMySubjectCollectionVerified`
|
|
165
|
-
- `normalizeCollectionStatusValue`
|
|
166
|
-
- `normalizeRateValue`
|
|
167
|
-
- `fetchAllCollections`
|
|
168
|
-
- `sortCollections`
|
|
169
|
-
- `executeCollectionListCommand` (line ~3410) — collection list handler with offset, API filter passthrough, and pagination
|
|
170
|
-
- `fetchAllCollections` (line ~4308) — parallel fetch with bounded concurrency, API filter passthrough, sequential fallback for unreliable totals
|
|
171
|
-
|
|
172
|
-
### Episodes
|
|
173
|
-
|
|
174
|
-
- preserve the Bangumi-specific distinction between subject collection progress and dedicated episode collection endpoints
|
|
175
|
-
- do not route anime / game / real subject progress through subject collection `ep_status`
|
|
176
|
-
- for book-type subjects, use the dedicated `book` commands (`book get`, `book ep`, `book vol`) instead of `episode` commands
|
|
177
|
-
- preserve the observed constraint that the parent subject must already be collected before episode writes and book progress writes
|
|
178
|
-
- do not assume `doing` is required for episode writes unless Bangumi behavior is revalidated and changed
|
|
179
|
-
- preserve the NSFW episode-list auth behavior: for `p1` requests, prefer private session cookie and fall back to Access Token without double-sending credentials; without a usable auth context, surface the misleading-404 caveat clearly
|
|
180
|
-
- preserve the book-type hint behavior: when a user targets a book-type subject with `episode list`, `episode watch`, or `episode comments <subject_id> <episode_number>`, suggest the correct `bgm book` command
|
|
181
|
-
|
|
182
|
-
Relevant helpers in `src/cli.js`:
|
|
183
|
-
|
|
184
|
-
- `executeEpisodeListCommand`
|
|
185
|
-
- `executeEpisodeStatusCommand`
|
|
186
|
-
- `executeEpisodeWatchCommand`
|
|
187
|
-
- `fetchMyEpisodeCollectionVerified`
|
|
188
|
-
- `normalizeEpisodeCollectionStatusValue`
|
|
189
|
-
- `normalizeEpisodeTypeFilter`
|
|
190
|
-
- `fetchAllEpisodes`
|
|
191
|
-
|
|
192
|
-
Relevant helpers in `src/commands/book.js`:
|
|
193
|
-
|
|
194
|
-
- `runBookCommand`
|
|
195
|
-
- `executeBookGetCommand`
|
|
196
|
-
- `executeBookEpCommand`
|
|
197
|
-
- `executeBookVolCommand`
|
|
198
|
-
- `ensureBookCollection`
|
|
199
|
-
|
|
200
|
-
## File Ownership Conventions
|
|
201
|
-
|
|
202
|
-
- reusable Bangumi API behavior belongs in `src/core/client.js`
|
|
203
|
-
- transport and request normalization belong in `src/core/http.js`
|
|
204
|
-
- config defaults, merge order, and persistence belong in `src/core/config.js`
|
|
205
|
-
- human-readable rendering and JSON passthrough belong in `src/core/output.js`
|
|
206
|
-
- command orchestration belongs in `src/cli.js`
|
|
207
|
-
- self-hosted OAuth service behavior belongs under `oauth-backend/src/`
|
|
208
|
-
|
|
209
|
-
Avoid adding parallel logic in `src/cli.js` when the behavior should live in a reusable core module.
|
|
210
|
-
|
|
211
|
-
## Documentation Conventions
|
|
212
|
-
|
|
213
|
-
- put repository documentation under `docs/`
|
|
214
|
-
- do not create a parallel top-level `doc/` directory
|
|
215
|
-
- keep published installable skills under the top-level `skills/` directory
|
|
216
|
-
- use `docs/skills/README.md` and `SKILLS.md` as indexes, not as duplicate skill payloads
|
|
217
|
-
- update `README.md`, localized READMEs, `docs/README.md`, `docs/skills/README.md`, `skills/README.md`, and `SKILLS.md` when skill discovery paths or names change
|
|
218
|
-
|
|
219
|
-
## Adding a New Command
|
|
220
|
-
|
|
221
|
-
When adding a new top-level command (e.g. `calendar`, `index`, `subject`), follow the three-layer convention:
|
|
222
|
-
|
|
223
|
-
1. **API client** — `src/core/client.js`
|
|
224
|
-
- Add an async method to `BangumiClient` (or the appropriate client class).
|
|
225
|
-
- Reuse `this.request()` with the correct endpoint path.
|
|
226
|
-
- Example pattern: `async getCalendar() { return this.request("/calendar"); }`
|
|
227
|
-
|
|
228
|
-
2. **Output formatting** — `src/core/output.js`
|
|
229
|
-
- Add a type-guard function (e.g. `isCalendarPayload(value)`) near the other guards at the bottom of the file.
|
|
230
|
-
- Add a formatter function (e.g. `formatCalendar(payload)`) for human-readable output.
|
|
231
|
-
- Wire the guard into `formatDisplayResult()` so `--json` passthrough and human rendering both work.
|
|
232
|
-
- Add help text in `buildUsageText()` under the appropriate `case`.
|
|
233
|
-
|
|
234
|
-
3. **Command handler** — `src/cli.js`
|
|
235
|
-
- Add an async `run<Command>Command(command, args, context)` handler.
|
|
236
|
-
- **Do not assume `getBangumiClient()` exists.** Look at existing handlers: some construct `new BangumiClient(getConfig())` directly. Copy the pattern used by the most similar handler.
|
|
237
|
-
- Wire the handler into the main `switch (group)` block in `main()`.
|
|
238
|
-
- **Pitfall — flag options become the `command` parameter.** The CLI's `main()` destructures argv as `[group, command, ...rest]`. When a user runs `bgm calendar --all`, the `--all` token becomes `command` and `args` (the `rest`) is empty. If your handler checks `args.includes("--all")`, it will silently miss the flag. **Fix:** merge `--` prefixed commands back into args before processing, following the pattern in `runStatusCommand`:
|
|
239
|
-
```js
|
|
240
|
-
const allArgs = command && String(command).startsWith("--") ? [command, ...args] : args;
|
|
241
|
-
const all = allArgs.includes("--all");
|
|
242
|
-
```
|
|
243
|
-
|
|
244
|
-
### CLI argument style convention
|
|
245
|
-
|
|
246
|
-
This project uses **subcommand-style** positional arguments for behavior selection, **not** `--flag` style. Study existing commands before choosing a style:
|
|
247
|
-
|
|
248
|
-
- `bgm status current` — subcommand `current`
|
|
249
|
-
- `bgm collection status <id> doing` — subcommand `status`, positional enum `doing`
|
|
250
|
-
- `bgm episode watch <id> 5` — subcommand `watch`, positional number
|
|
251
|
-
|
|
252
|
-
Flags (`--`) are reserved for **options** (modifiers), not for behavior selection:
|
|
253
|
-
- `bgm subject search "ghost" --type anime --limit 5` — `--type` and `--limit` are options
|
|
254
|
-
|
|
255
|
-
**When adding a new command that selects a mode (e.g. `all`, `today`, `monday`), use positional subcommands, not `--flags`.**
|
|
256
|
-
|
|
257
|
-
Bad:
|
|
258
|
-
```
|
|
259
|
-
bgm calendar --all # violates convention
|
|
260
|
-
bgm calendar --monday # violates convention
|
|
38
|
+
```bash
|
|
39
|
+
node --check src/core/client.js
|
|
40
|
+
node --check src/core/output.js
|
|
41
|
+
node --check src/cli.js
|
|
42
|
+
npm test
|
|
261
43
|
```
|
|
262
44
|
|
|
263
|
-
|
|
264
|
-
```
|
|
265
|
-
bgm calendar all # follows convention
|
|
266
|
-
bgm calendar monday # follows convention
|
|
267
|
-
bgm calendar mon # abbreviated form also OK
|
|
268
|
-
```
|
|
269
|
-
|
|
270
|
-
If an earlier draft used `--flag` style and may already be in users' muscle memory, preserve backward compatibility by also accepting the old `--flag` forms (merge `--` prefixed `command` back into `args`).
|
|
271
|
-
|
|
272
|
-
### Verification checklist for new commands
|
|
273
|
-
|
|
274
|
-
- `node --check src/core/client.js`
|
|
275
|
-
- `node --check src/core/output.js`
|
|
276
|
-
- `node --check src/cli.js`
|
|
277
|
-
- `node src/cli.js <new-command>` (human-readable smoke test)
|
|
278
|
-
- `node src/cli.js --json <new-command>` (JSON smoke test)
|
|
279
|
-
- `node src/cli.js <new-command> --help` (help text smoke test)
|
|
280
|
-
- `node src/cli.js --help` (ensure the command appears in the main help list)
|
|
281
|
-
|
|
282
|
-
For book commands specifically, also verify:
|
|
283
|
-
- `node src/cli.js book get --help`
|
|
284
|
-
- `node src/cli.js book ep --help`
|
|
285
|
-
- `node src/cli.js book vol --help`
|
|
286
|
-
- non-book subjects are rejected with a clear message
|
|
287
|
-
- book-type hints appear when `episode list` / `episode watch` / `episode comments` target a book subject
|
|
288
|
-
|
|
289
|
-
If networked or authenticated behavior cannot be exercised, say so explicitly instead of implying full end-to-end validation.
|
|
290
|
-
|
|
291
|
-
### Output language policy
|
|
292
|
-
|
|
293
|
-
All non-API output strings in `src/` must be **English only**. API-returned data (subject names, weekday labels from Bangumi, etc.) may contain any language. The TUI layer is the only exception where localized strings are acceptable.
|
|
294
|
-
|
|
295
|
-
This applies to:
|
|
296
|
-
- Help text and usage descriptions in `src/core/output.js`
|
|
297
|
-
- Error messages in `src/core/output.js` and `src/cli.js`
|
|
298
|
-
- Mock data in tests under `test/`
|
|
299
|
-
- Table headers, column names, and CLI prompts
|
|
300
|
-
|
|
301
|
-
Bad:
|
|
302
|
-
```
|
|
303
|
-
// In src/core/output.js help text
|
|
304
|
-
["bgm calendar", "显示今日番组表"] // violates policy
|
|
305
|
-
```
|
|
306
|
-
|
|
307
|
-
Good:
|
|
308
|
-
```
|
|
309
|
-
["bgm calendar", "Show today's anime broadcast schedule"] // correct
|
|
310
|
-
```
|
|
311
|
-
|
|
312
|
-
### Testing conventions
|
|
313
|
-
|
|
314
|
-
Use Node.js built-in `node:test` + `node:assert`. Do **not** add external test dependencies like `vitest`, `jest`, or `mocha`.
|
|
315
|
-
|
|
316
|
-
- Place tests under `test/`
|
|
317
|
-
- Name files `*.test.js`
|
|
318
|
-
- Use ESM imports (`import { describe, it } from "node:test"`)
|
|
319
|
-
- For CLI integration tests, use `spawnSync` to invoke `node src/cli.js`
|
|
320
|
-
- For unit tests on formatters, import directly from `src/core/output.js`
|
|
321
|
-
- Add `"test": "node --test"` to `package.json` scripts
|
|
322
|
-
- GitHub Actions should run `npm test` on push/PR/release
|
|
323
|
-
|
|
324
|
-
Example test pattern:
|
|
325
|
-
```js
|
|
326
|
-
import { spawnSync } from "node:child_process";
|
|
327
|
-
import { describe, it } from "node:test";
|
|
328
|
-
import assert from "node:assert";
|
|
329
|
-
|
|
330
|
-
function run(args) {
|
|
331
|
-
return spawnSync("node", ["src/cli.js", ...args], { encoding: "utf-8", cwd: process.cwd() });
|
|
332
|
-
}
|
|
333
|
-
```
|
|
334
|
-
|
|
335
|
-
### Test what the CLI does, not what the API returns
|
|
336
|
-
|
|
337
|
-
Real API calls are acceptable for **1 smoke test per command group** to confirm end-to-end wiring, but the bulk of tests should validate the **CLI's own logic** using mock data:
|
|
338
|
-
|
|
339
|
-
- **Parameter parsing and normalization** — e.g. `parseFlags()`, `normalizeSubjectTypeFilter()`, `normalizeCollectionStatusFilter()`
|
|
340
|
-
- **Formatting and rendering** — e.g. `formatDisplayResult()` with constructed payloads
|
|
341
|
-
- **Filtering, sorting, slicing** — e.g. `sortCollections()`, client-side pagination logic
|
|
342
|
-
- **Boundary conditions** — empty arrays, missing fields, `undefined` scores
|
|
343
|
-
|
|
344
|
-
**Do not write multiple integration tests that merely exercise the upstream Bangumi API** (e.g. testing that `calendar mon` returns Monday, `calendar sun` returns Sunday, `calendar all` returns 7 days). Those test Bangumi's API contract, not the CLI. One default-path smoke test per group is enough.
|
|
345
|
-
|
|
346
|
-
**Shift test budget toward high-frequency commands.** `collection` and `subject` are heavily used; they deserve deep unit coverage for filtering/sorting/formatting. `calendar` is read-only and low-complexity; 1 integration + 2 formatting tests is sufficient.
|
|
347
|
-
|
|
348
|
-
If the CLI code tightly couples API calls with logic (common in `src/cli.js` handlers), prefer extracting the pure logic into testable functions over adding more integration tests. Integration tests are slow, flaky, and burn CI minutes.
|
|
349
|
-
|
|
350
|
-
### Release conventions
|
|
351
|
-
|
|
352
|
-
Releases are automatic and the version lives in git tags (`vX.Y.Z`), like magpie. Do not bump versions by hand.
|
|
353
|
-
|
|
354
|
-
- Every push to `main` that has commits since the latest tag releases the next **patch** version: `.github/workflows/release.yml` runs the tests, creates the tag and GitHub Release, and publishes to npm. `scripts/next-version.sh` decides the version.
|
|
355
|
-
- `package.json` carries the placeholder `0.0.0-dev`. The workflow stamps the real version into it inside the runner right before `npm publish` and never commits it back. A source checkout therefore reports `0.0.0-dev`.
|
|
356
|
-
- Put `[skip release]` in the head commit subject (first line) to push to `main` without releasing.
|
|
357
|
-
- For a minor or major bump, push a commit with `[skip release]`, then tag that commit and push only the tag: `git tag v1.2.0 && git push origin v1.2.0`. A pushed `v*` tag releases exactly that version.
|
|
358
|
-
- Before pushing, verify: `npm test`, `node src/cli.js --help`, `node src/cli.js --version`.
|
|
359
|
-
- Use semantic versioning: automatic releases are always patch; choose minor for features/commands and major for breaking changes by tagging as above.
|
|
360
|
-
|
|
361
|
-
## Environment Conventions
|
|
362
|
-
|
|
363
|
-
- Node.js `>= 20`
|
|
364
|
-
- package type is ESM
|
|
365
|
-
- config precedence is: built-in defaults, `bgm-dev.env`, runtime `config.json`, environment variables
|
|
366
|
-
- use existing install scripts under `scripts/` before inventing new manual setup steps
|
|
45
|
+
Unit tests use Node.js built-in `node:test` and `node:assert`. Test CLI behavior (parsing, formatting, sorting) using mock data rather than repeatedly hitting upstream APIs.
|
|
367
46
|
|
|
368
|
-
##
|
|
47
|
+
## Release Process
|
|
369
48
|
|
|
370
|
-
-
|
|
371
|
-
- when the task is only about end-user installation and auth rather than repository changes
|
|
49
|
+
Releases trigger automatically via git tags (`vX.Y.Z`). `package.json` holds a `0.0.0-dev` placeholder; do not bump versions manually in files. Push commits with `[skip release]` to bypass automated patch releases.
|
|
@@ -1,259 +1,58 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: "bgm-cli-operate"
|
|
3
|
-
description: "Use
|
|
3
|
+
description: "Use to install, configure, authenticate, and run bgm-cli for Bangumi operations: subjects, episodes, books, collections, user data, groups, blogs, timelines, notifications, and Turnstile-gated writes."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# bgm-cli Operate
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
Operate `bgm-cli` on macOS, Linux, or Windows. Prefer non-interactive CLI commands and `--json` for automation.
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
## Discovery and Runtime Context
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
## Use This Skill For
|
|
15
|
-
|
|
16
|
-
- detecting whether `bgm` or `./bgm` is available
|
|
17
|
-
- installing `bgm-cli` on macOS, Linux, or Windows when needed
|
|
18
|
-
- choosing between remote managed install and repository-local install-path setup
|
|
19
|
-
- setting or checking Bangumi auth
|
|
20
|
-
- reading user, notification, subject, episode, group, collection, character, person, blog, index, timeline, trending, and calendar data
|
|
21
|
-
- performing supported collection writes, episode-progress writes, book-progress writes, notification clears, subject/group topic writes, character/person/blog/index comment writes, index writes, and supported timeline writes
|
|
22
|
-
- using Bangumi emote codes like `(bgm54)` in comments, where the site renders them as emojis
|
|
23
|
-
- using reaction-style `like` commands with target-specific numeric sticker values
|
|
24
|
-
- preferring `--json` for agent consumption
|
|
25
|
-
- troubleshooting PATH, Node, auth, Access Token, session, and Turnstile problems
|
|
26
|
-
|
|
27
|
-
## Do Not Use This Skill For
|
|
28
|
-
|
|
29
|
-
- editing the `bgm-cli` repository itself
|
|
30
|
-
- changing command behavior or output contracts
|
|
31
|
-
- debugging source-level implementation details
|
|
32
|
-
- promising Bangumi site features that the CLI does not expose
|
|
33
|
-
|
|
34
|
-
## Primary Contract
|
|
35
|
-
|
|
36
|
-
An agent using only this skill should be able to:
|
|
37
|
-
|
|
38
|
-
1. detect the usable executable
|
|
39
|
-
2. install `bgm-cli` if it is missing
|
|
40
|
-
3. bring the user to a usable auth state
|
|
41
|
-
4. run the requested task with the narrowest correct command
|
|
42
|
-
5. verify important writes and report unsupported scope plainly
|
|
43
|
-
|
|
44
|
-
## Default Workflow
|
|
45
|
-
|
|
46
|
-
### 1. Detect the executable first
|
|
47
|
-
|
|
48
|
-
Try in this order:
|
|
49
|
-
|
|
50
|
-
1. `bgm --help`
|
|
51
|
-
2. `./bgm --help` when operating from a repository checkout
|
|
52
|
-
|
|
53
|
-
Once one works, use that executable consistently.
|
|
54
|
-
|
|
55
|
-
Preferred order:
|
|
56
|
-
|
|
57
|
-
1. `bgm`
|
|
58
|
-
2. `./bgm`
|
|
59
|
-
|
|
60
|
-
### 2. Install if missing
|
|
61
|
-
|
|
62
|
-
If neither executable works, install the CLI.
|
|
63
|
-
|
|
64
|
-
Preferred install choice:
|
|
65
|
-
|
|
66
|
-
1. remote managed install when the user just wants a working `bgm`
|
|
67
|
-
2. repository-local install-path setup when the user is already in a cloned checkout and wants that checkout exposed as `bgm`
|
|
68
|
-
3. direct `./bgm` use when the user only needs commands inside the current checkout
|
|
69
|
-
|
|
70
|
-
Use `references/install-and-auth.md`.
|
|
71
|
-
|
|
72
|
-
### 3. Establish auth before real work
|
|
73
|
-
|
|
74
|
-
Preferred auth path:
|
|
75
|
-
|
|
76
|
-
1. `bgm --init` for guided setup, choosing the recommended official Bangumi login
|
|
77
|
-
2. `bgm auth login` when the user wants to start the official login directly
|
|
78
|
-
3. `bgm auth set-token <access_token>` when the user already has an Access Token or needs the token channel for scripting
|
|
79
|
-
4. OAuth helper flows only when the user explicitly wants them
|
|
80
|
-
|
|
81
|
-
Verify auth before important writes:
|
|
82
|
-
|
|
83
|
-
```bash
|
|
84
|
-
bgm auth status
|
|
85
|
-
bgm user me
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
If only the Access Token channel needs validation, use:
|
|
89
|
-
|
|
90
|
-
```bash
|
|
91
|
-
bgm auth token-status
|
|
92
|
-
```
|
|
93
|
-
|
|
94
|
-
If only private `p1` session state matters, use:
|
|
12
|
+
Do not rely on memorized command flags or references. Query runtime commands directly:
|
|
95
13
|
|
|
96
14
|
```bash
|
|
97
|
-
bgm
|
|
15
|
+
bgm --help # Compact command overview
|
|
16
|
+
bgm <group> --help # Subcommands and flags (e.g., bgm episode --help)
|
|
17
|
+
bgm --skill operate <reference> # Built-in reference documents:
|
|
18
|
+
# commands, install-and-auth, troubleshooting,
|
|
19
|
+
# community-boundaries, reactions
|
|
98
20
|
```
|
|
99
21
|
|
|
100
|
-
|
|
22
|
+
## Setup and Auth
|
|
101
23
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
-
|
|
105
|
-
-
|
|
106
|
-
-
|
|
24
|
+
1. Executable check: Try `bgm`, then `./bgm`. If missing, follow `references/install-and-auth.md`.
|
|
25
|
+
2. Authentication flow:
|
|
26
|
+
- Guided login: `bgm --init` or `bgm auth login`.
|
|
27
|
+
- Access token: `bgm auth set-token <token>`.
|
|
28
|
+
- Check state: `bgm auth status` or `bgm user me`.
|
|
107
29
|
|
|
108
|
-
|
|
30
|
+
## Operational Guidelines
|
|
109
31
|
|
|
110
|
-
|
|
32
|
+
- JSON automation: Pass `--json` for machine-readable output.
|
|
33
|
+
- Link resolution: Pass Bangumi URLs directly to `bgm "<url>"` or `bgm url "<url>"` instead of manual URL parsing. Use `--dry-run` to preview offline. Always quote URLs containing `#`.
|
|
34
|
+
- Episodes vs. books:
|
|
35
|
+
- Anime, games, and real subjects: Use `bgm episode` (`episode watch`, `episode status`).
|
|
36
|
+
- Books: Use `bgm book` (`book ep`, `book vol`).
|
|
37
|
+
- Prerequisite: Subject must be in collection first.
|
|
38
|
+
- Turnstile CAPTCHA:
|
|
39
|
+
- Gated writes (topic creation, replies, comments, timeline posts) require Cloudflare verification.
|
|
40
|
+
- In agent environments without a local browser, run `bgm auth turnstile`, output the URL for the user to complete manually, then pass the returned token via `--turnstile-token <token>`.
|
|
41
|
+
- Reactions (贴贴): Stickers use fixed integer IDs (e.g., `140` for +1). See `references/reactions.md`.
|
|
42
|
+
- Write verification: Query updated state after write operations (e.g., `bgm --json collection get <id>`).
|
|
111
43
|
|
|
112
|
-
|
|
113
|
-
bgm --json --url "https://bangumi.tv/group/topic/469977#post_4029724" --dry-run
|
|
114
|
-
bgm --json "https://bangumi.tv/group/topic/469977#post_4029724"
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
- Three equivalent forms: `bgm <url>`, `bgm url <url>`, `bgm --url <url>` (`-url` is an alias).
|
|
118
|
-
- Hosts: `bgm.tv`, `bangumi.tv`, `chii.in`, `next.bgm.tv`, `api.bgm.tv`; `https://` and `www.` are optional.
|
|
119
|
-
- Run `--dry-run` first when the mapping matters; it prints the resolved command offline and makes no request.
|
|
120
|
-
- Resolution is read-only. A link never triggers a write, so keep using the explicit write commands.
|
|
121
|
-
- `#post_<id>` resolves to that single reply, not the whole topic.
|
|
122
|
-
- `--json` returns the target command's payload plus a `resolvedFrom` field (`url`, `site`, `command`, `args`), so downstream parsing is unchanged.
|
|
123
|
-
- Always quote links containing `#`, otherwise the shell truncates them.
|
|
124
|
-
- Unsupported paths fail with a `Did you mean: bgm ...` suggestion; follow the suggestion instead of retrying the link.
|
|
125
|
-
- Run `bgm url --help` for the full list of supported link shapes.
|
|
126
|
-
|
|
127
|
-
### 6. Verify important writes
|
|
128
|
-
|
|
129
|
-
For collection, episode-progress, notification, subject/group topic, character/person/blog/index comment, index, or timeline writes, read back the final state when the result matters.
|
|
130
|
-
|
|
131
|
-
Examples:
|
|
132
|
-
|
|
133
|
-
```bash
|
|
134
|
-
bgm --json collection get 348335
|
|
135
|
-
bgm --json episode list 348335 --type main --limit 5
|
|
136
|
-
bgm --json group topic 498114
|
|
137
|
-
bgm --json subject topic 29892
|
|
138
|
-
```
|
|
139
|
-
|
|
140
|
-
## Operational Rules
|
|
141
|
-
|
|
142
|
-
- If installation is required and terminal access is available, perform the installation.
|
|
143
|
-
- If auth is required and missing, prefer `bgm --init` or `bgm auth login` in an interactive terminal.
|
|
144
|
-
- Treat Access Token as a preserved second channel for users who already have a token or need scripting compatibility.
|
|
145
|
-
- Treat `session-login` as manual session import helper state, not as the normal official login path.
|
|
146
|
-
- Do not send both private session and Access Token credentials for `p1` requests; current CLI behavior prefers the private session cookie when it is saved.
|
|
147
|
-
- Treat book progress as separate from episode progress; use `bgm book get/ep/vol` for book-type subjects and `bgm episode` commands for anime/game/real subjects.
|
|
148
|
-
- Treat book writes as requiring that the parent subject is already in the user's collection and that the subject is a book-type entry.
|
|
149
|
-
- Treat episode progress as separate from the subject collection `ep_status` field for non-book subjects; prefer the dedicated `episode` commands.
|
|
150
|
-
- Treat episode writes as requiring that the parent subject is already in the user's collection.
|
|
151
|
-
- Do not assume the parent collection must be `doing`; Bangumi currently allows episode writes under `wish`, `collect`, `doing`, `on_hold`, and `dropped` as long as the subject is collected.
|
|
152
|
-
- Treat `episode watch` as a main-story helper only. For SP / OP / ED writes, use `episode status <episode_id> ...` directly.
|
|
153
|
-
- Treat NSFW episode listing as auth-sensitive. Without a usable auth context, Bangumi may return a misleading `404` instead of a clear auth error. For `p1` requests, the CLI prefers a private session cookie and falls back to Access Token when no session is saved.
|
|
154
|
-
- Treat reactions (贴贴) as stickers, never as likes. A `reactions[].value` in `--json` output and a `like` command value are sticker ids from a fixed set of twelve; only `140` (+1) means agreement and `141` is a question mark. Read `references/reactions.md` before interpreting or posting one.
|
|
155
|
-
- Treat reaction-style `like` values as target-specific. Reply-type targets accept all twelve current values; subject collection comments accept a subset of eight.
|
|
156
|
-
- Treat `bgm auth turnstile` as official-hosted-first and local-helper-second. Use `--manual` only when you explicitly need to force the local helper path.
|
|
157
|
-
- Treat subject/group topic creation and replies as Turnstile-gated operations.
|
|
158
|
-
- Treat character/person/blog comment writes as Turnstile-gated operations; blog comment writes are still experimental.
|
|
159
|
-
- Treat timeline `say` and `reply` as Turnstile-gated operations.
|
|
160
|
-
- Treat notification support as list/read and mark-read only; accepting or rejecting friend requests is not exposed as a notify command.
|
|
161
|
-
- Treat friend/follower commands as read-only list commands; friend/follow relationship mutations are not exposed.
|
|
162
|
-
- Use `bgm setup update` only for managed installs created by the remote installer.
|
|
163
|
-
- Use `bgm setup install-path` only when the user wants the current checkout exposed as global `bgm`.
|
|
164
|
-
- **Agent Turnstile human-in-the-loop for posting**: The agent cannot complete Cloudflare Turnstile CAPTCHA automatically. When the user asks to create a group topic (`group create-topic`) or reply (`group reply`), and the CLI returns a Turnstile-required error, the agent must: 1) run `bgm auth turnstile` to generate the official verification URL; 2) send the URL to the user; 3) wait for the user to complete verification manually and return the token; 4) re-run the post/reply command with `--turnstile-token`. Do not rely on the terminal auto-callback succeeding, because automatic browser launch is usually unavailable in agent environments.
|
|
165
|
-
- Do not infer unsupported community actions from the Bangumi website alone.
|
|
166
|
-
|
|
167
|
-
## Fast Start Commands
|
|
168
|
-
|
|
169
|
-
### Capability and auth
|
|
170
|
-
|
|
171
|
-
```bash
|
|
172
|
-
bgm --help
|
|
173
|
-
bgm auth status
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
### Minimum ready state from zero
|
|
177
|
-
|
|
178
|
-
```bash
|
|
179
|
-
bgm --init
|
|
180
|
-
bgm auth status
|
|
181
|
-
bgm user me
|
|
182
|
-
```
|
|
183
|
-
|
|
184
|
-
### Common reads
|
|
44
|
+
## Quick Reference
|
|
185
45
|
|
|
186
46
|
```bash
|
|
187
47
|
bgm --json user me
|
|
188
|
-
bgm --json
|
|
189
|
-
bgm --json
|
|
190
|
-
bgm --json
|
|
191
|
-
bgm --json
|
|
192
|
-
bgm --json
|
|
193
|
-
bgm
|
|
194
|
-
bgm
|
|
195
|
-
bgm
|
|
196
|
-
bgm
|
|
197
|
-
bgm
|
|
198
|
-
bgm --json episode comments 253 1
|
|
199
|
-
bgm --json book get 3510
|
|
200
|
-
bgm --json collection get 253
|
|
201
|
-
bgm --json collection characters --user sai --limit 10
|
|
202
|
-
bgm --json collection persons --user sai --limit 10
|
|
203
|
-
bgm --json character search "夏娜" --limit 5
|
|
204
|
-
bgm --json person search "坂本真綾" --career seiyu --limit 5
|
|
205
|
-
bgm --json group topics boring --limit 20
|
|
206
|
-
bgm --json blog get 371953
|
|
207
|
-
bgm --json index get 1
|
|
208
|
-
bgm --json timeline list --mode friends --limit 10
|
|
209
|
-
bgm --json timeline user sai --limit 10
|
|
210
|
-
bgm --json timeline replies 123456
|
|
211
|
-
bgm --json calendar
|
|
212
|
-
bgm --json calendar all
|
|
213
|
-
bgm --json url https://bgm.tv/subject/253/characters
|
|
214
|
-
bgm --json --url https://bgm.tv/anime/list/sai/collect --dry-run
|
|
48
|
+
bgm --json subject get <id>
|
|
49
|
+
bgm --json subject search "<keyword>" --type anime --limit 5
|
|
50
|
+
bgm --json collection get <id>
|
|
51
|
+
bgm --json collection status <id> <wish|collect|doing|on_hold|dropped>
|
|
52
|
+
bgm --json episode list <id> --type main --limit 10
|
|
53
|
+
bgm episode watch <subject_id> <ep_number>
|
|
54
|
+
bgm book ep <subject_id> <chapter>
|
|
55
|
+
bgm group topic <topic_id>
|
|
56
|
+
bgm group reply <topic_id> "<content>" --turnstile-token <token>
|
|
57
|
+
bgm "<bangumi_url>"
|
|
215
58
|
```
|
|
216
|
-
|
|
217
|
-
### Common writes
|
|
218
|
-
|
|
219
|
-
```bash
|
|
220
|
-
bgm collection status 253 doing
|
|
221
|
-
bgm book ep 3510 10
|
|
222
|
-
bgm book vol 3510 2
|
|
223
|
-
bgm episode watch 253 1
|
|
224
|
-
bgm episode status 103232 watched
|
|
225
|
-
bgm collection rate 253 8
|
|
226
|
-
bgm collection comment 253 "Backfill"
|
|
227
|
-
bgm notify clear 123456
|
|
228
|
-
bgm subject reply 29892 "Reply content" --turnstile-token YOUR_TOKEN
|
|
229
|
-
bgm group reply 498114 "Reply content" --turnstile-token YOUR_TOKEN
|
|
230
|
-
bgm character comment 1 "Comment content" --turnstile-token YOUR_TOKEN
|
|
231
|
-
bgm person comment 1 "Comment content" --turnstile-token YOUR_TOKEN
|
|
232
|
-
bgm blog reply 371953 "Test comment" --turnstile-token YOUR_TOKEN
|
|
233
|
-
bgm timeline say "off work" --turnstile-token YOUR_TOKEN
|
|
234
|
-
bgm timeline reply 123456 "seen" --turnstile-token YOUR_TOKEN
|
|
235
|
-
bgm index comment 1 "Nice index" --turnstile-token YOUR_TOKEN
|
|
236
|
-
```
|
|
237
|
-
|
|
238
|
-
## Command Coverage
|
|
239
|
-
|
|
240
|
-
Read these references before guessing. If you cannot read files from this skill's directory, print any of them with `bgm --skill operate <name>` (for example `bgm --skill operate commands`):
|
|
241
|
-
|
|
242
|
-
- `references/install-and-auth.md`
|
|
243
|
-
- `references/commands.md`
|
|
244
|
-
- `references/troubleshooting.md`
|
|
245
|
-
- `references/community-boundaries.md`
|
|
246
|
-
- `references/reactions.md`
|
|
247
|
-
|
|
248
|
-
## Output Expectations
|
|
249
|
-
|
|
250
|
-
When reporting back to a user or another agent, always say:
|
|
251
|
-
|
|
252
|
-
- which executable was used: `bgm` or `./bgm`
|
|
253
|
-
- whether installation was needed
|
|
254
|
-
- whether auth was already present or had to be set up
|
|
255
|
-
- which commands were run
|
|
256
|
-
- whether results came from JSON output or human-readable output
|
|
257
|
-
- when a pasted link was resolved, which command it resolved to (from `--dry-run` or the `resolvedFrom` field)
|
|
258
|
-
- for episode operations, whether the parent subject was already collected and whether NSFW auth restrictions affected the task
|
|
259
|
-
- what could not be completed because of missing auth, install failure, or unsupported CLI scope
|
package/src/commands/search.js
CHANGED
|
@@ -20,14 +20,19 @@ import {
|
|
|
20
20
|
searchBlogs,
|
|
21
21
|
} from "../core/community-api.js";
|
|
22
22
|
import { CommandError, printResult } from "../core/output.js";
|
|
23
|
-
import { firstPositional, parseFlags } from "../utils/args.js";
|
|
24
|
-
import {
|
|
23
|
+
import { firstPositional, parseFlags, splitFilterValues } from "../utils/args.js";
|
|
24
|
+
import {
|
|
25
|
+
normalizeNonNegativeInteger,
|
|
26
|
+
normalizePageSize,
|
|
27
|
+
parseOptionalBoolean,
|
|
28
|
+
} from "../utils/helpers.js";
|
|
29
|
+
import { normalizeSubjectTypeName } from "../utils/validators.js";
|
|
25
30
|
|
|
26
31
|
export async function runSearchCommand(command, args, context) {
|
|
27
32
|
switch (command) {
|
|
28
33
|
case "subject":
|
|
29
34
|
case "subjects": {
|
|
30
|
-
const result = await executeEntitySearch("subjects", args, searchSubjects);
|
|
35
|
+
const result = await executeEntitySearch("subjects", args, searchSubjects, { allowSubjectType: true });
|
|
31
36
|
printResult(result, context);
|
|
32
37
|
return;
|
|
33
38
|
}
|
|
@@ -77,7 +82,7 @@ export async function runSearchCommand(command, args, context) {
|
|
|
77
82
|
}
|
|
78
83
|
default:
|
|
79
84
|
throw new CommandError(
|
|
80
|
-
"Usage: bgm search <subject|user|group|topic|subject-topic|reply|index|blog> <keyword> [--limit n] [--offset n] [--sort <sort>]",
|
|
85
|
+
"Usage: bgm search <subject|user|group|topic|subject-topic|reply|index|blog> <keyword> [--limit n] [--offset n] [--sort <sort>] [--user <name>] [--group <slug>] [--exact] [--include <nsfw|blocked>] [--exclude nsfw] [--type <type>] [--source <source>]",
|
|
81
86
|
);
|
|
82
87
|
}
|
|
83
88
|
}
|
|
@@ -86,15 +91,61 @@ const REPLY_SOURCES = new Set([
|
|
|
86
91
|
"all", "group", "subject", "episode", "ep", "character", "crt", "person", "prsn", "blog",
|
|
87
92
|
]);
|
|
88
93
|
|
|
89
|
-
|
|
94
|
+
// SearchEncore 内联指令的合法取值(写入 q,而非独立 query 参数)。
|
|
95
|
+
const DIRECTIVE_INCLUDE_VALUES = new Set(["nsfw", "blocked"]);
|
|
96
|
+
const DIRECTIVE_EXCLUDE_VALUES = new Set(["nsfw"]);
|
|
97
|
+
|
|
98
|
+
function directiveValues(flag, flagName, { allowed, lowercase = true } = {}) {
|
|
99
|
+
if (flag === undefined) {
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
if (flag === true) {
|
|
103
|
+
throw new CommandError(`--${flagName} requires a value.`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return splitFilterValues(flag).map((entry) => {
|
|
107
|
+
const raw = String(entry);
|
|
108
|
+
const value = lowercase ? raw.toLowerCase() : raw;
|
|
109
|
+
if (allowed && !allowed.has(value)) {
|
|
110
|
+
throw new CommandError(
|
|
111
|
+
`Invalid --${flagName}: ${entry}. Use one of: ${[...allowed].join(", ")}.`,
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
return value;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function executeEntitySearch(resource, args, searchFn, { allowSource = false, allowSubjectType = false } = {}) {
|
|
90
119
|
const options = parseFlags(args);
|
|
91
|
-
const
|
|
92
|
-
if (!
|
|
120
|
+
const rawKeyword = firstPositional(options);
|
|
121
|
+
if (!rawKeyword) {
|
|
93
122
|
throw new CommandError(
|
|
94
|
-
`Usage: bgm search ${resource} <keyword> [--limit n] [--offset n] [--sort <sort>]${allowSource ? " [--source <source>]" : ""}`,
|
|
123
|
+
`Usage: bgm search ${resource} <keyword> [--limit n] [--offset n] [--sort <sort>] [--user <name>] [--group <slug>] [--exact] [--include <nsfw|blocked>] [--exclude nsfw]${allowSubjectType ? " [--type <book|anime|music|game|real>]" : ""}${allowSource ? " [--source <source>]" : ""}`,
|
|
95
124
|
);
|
|
96
125
|
}
|
|
97
126
|
|
|
127
|
+
// 通用指令:用户名/组 slug 保留原始大小写,不做小写归一化。
|
|
128
|
+
const users = directiveValues(options.user, "user", { lowercase: false });
|
|
129
|
+
const groups = directiveValues(options.group, "group", { lowercase: false });
|
|
130
|
+
const includes = directiveValues(options.include, "include", { allowed: DIRECTIVE_INCLUDE_VALUES });
|
|
131
|
+
const excludes = directiveValues(options.exclude, "exclude", { allowed: DIRECTIVE_EXCLUDE_VALUES });
|
|
132
|
+
const exact = parseOptionalBoolean(options.exact);
|
|
133
|
+
|
|
134
|
+
// --type 只对 subject 资源生效;其他资源传了会被忽略(与服务端忽略不适用指令的语义一致)。
|
|
135
|
+
const subjectTypes = allowSubjectType
|
|
136
|
+
? directiveValues(options.type, "type").map((entry) => normalizeSubjectTypeName(entry))
|
|
137
|
+
: [];
|
|
138
|
+
|
|
139
|
+
const directives = [
|
|
140
|
+
...users.map((name) => `user:${name}`),
|
|
141
|
+
...groups.map((slug) => `group:${slug}`),
|
|
142
|
+
...subjectTypes.map((name) => `type:${name}`),
|
|
143
|
+
...includes.map((value) => `include:${value}`),
|
|
144
|
+
...excludes.map((value) => `exclude:${value}`),
|
|
145
|
+
...(exact === true ? ["exact:true"] : []),
|
|
146
|
+
];
|
|
147
|
+
const keyword = directives.length > 0 ? `${rawKeyword} ${directives.join(" ")}` : rawKeyword;
|
|
148
|
+
|
|
98
149
|
const query = {
|
|
99
150
|
q: keyword,
|
|
100
151
|
limit: normalizePageSize(options.limit),
|
|
@@ -121,10 +172,16 @@ async function executeEntitySearch(resource, args, searchFn, { allowSource = fal
|
|
|
121
172
|
resource: `community-${resource}`,
|
|
122
173
|
title: `SearchEncore: ${resource}`,
|
|
123
174
|
filters: {
|
|
124
|
-
keyword,
|
|
175
|
+
keyword: rawKeyword,
|
|
125
176
|
limit: query.limit,
|
|
126
177
|
offset: query.offset,
|
|
127
178
|
sort: query.sort,
|
|
179
|
+
...(users.length > 0 ? { user: users } : {}),
|
|
180
|
+
...(groups.length > 0 ? { group: groups } : {}),
|
|
181
|
+
...(subjectTypes.length > 0 ? { type: subjectTypes } : {}),
|
|
182
|
+
...(includes.length > 0 ? { include: includes } : {}),
|
|
183
|
+
...(excludes.length > 0 ? { exclude: excludes } : {}),
|
|
184
|
+
...(exact === true ? { exact: true } : {}),
|
|
128
185
|
...(query.source ? { source: query.source } : {}),
|
|
129
186
|
},
|
|
130
187
|
};
|
package/src/utils/validators.js
CHANGED
|
@@ -38,6 +38,10 @@ export const SUBJECT_TYPE_MAP = {
|
|
|
38
38
|
real: 6,
|
|
39
39
|
};
|
|
40
40
|
|
|
41
|
+
const SUBJECT_TYPE_NAME_MAP = Object.fromEntries(
|
|
42
|
+
Object.entries(SUBJECT_TYPE_MAP).map(([name, id]) => [id, name]),
|
|
43
|
+
);
|
|
44
|
+
|
|
41
45
|
export const COLLECTION_STATUS_MAP = {
|
|
42
46
|
wish: 1,
|
|
43
47
|
collect: 2,
|
|
@@ -140,6 +144,19 @@ export function normalizeSubjectType(value) {
|
|
|
140
144
|
return normalized;
|
|
141
145
|
}
|
|
142
146
|
|
|
147
|
+
/**
|
|
148
|
+
* 归一化为规范的小写类型名(book|anime|music|game|real),
|
|
149
|
+
* 供需要字符串类型名而非数字 ID 的场景使用(如 SearchEncore 的 `type:` 指令)。
|
|
150
|
+
*/
|
|
151
|
+
export function normalizeSubjectTypeName(value) {
|
|
152
|
+
const numeric = normalizeSubjectType(value);
|
|
153
|
+
if (numeric === undefined) {
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return SUBJECT_TYPE_NAME_MAP[numeric];
|
|
158
|
+
}
|
|
159
|
+
|
|
143
160
|
export function normalizeSubjectTypeFilter(value) {
|
|
144
161
|
if (value === undefined || value === null || value === "") {
|
|
145
162
|
return [];
|