@aronnaxlin/bgm-cli 1.0.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.
Files changed (46) hide show
  1. package/LICENSE +660 -0
  2. package/README.en.md +122 -0
  3. package/README.md +127 -0
  4. package/README.zh-TW.md +122 -0
  5. package/package.json +41 -0
  6. package/src/cli.js +993 -0
  7. package/src/commands/blog.js +213 -0
  8. package/src/commands/calendar.js +32 -0
  9. package/src/commands/character.js +291 -0
  10. package/src/commands/collection.js +418 -0
  11. package/src/commands/episode.js +379 -0
  12. package/src/commands/group.js +488 -0
  13. package/src/commands/index.js +362 -0
  14. package/src/commands/notify.js +74 -0
  15. package/src/commands/person.js +297 -0
  16. package/src/commands/status.js +74 -0
  17. package/src/commands/subject.js +537 -0
  18. package/src/commands/timeline.js +288 -0
  19. package/src/commands/trending.js +58 -0
  20. package/src/commands/tui.js +1537 -0
  21. package/src/commands/user.js +83 -0
  22. package/src/core/client.js +2065 -0
  23. package/src/core/config.js +450 -0
  24. package/src/core/http.js +144 -0
  25. package/src/core/output.js +3888 -0
  26. package/src/core/proxy.js +47 -0
  27. package/src/core/reactions.js +62 -0
  28. package/src/core/turnstile.js +526 -0
  29. package/src/data/bangumi-emotes.json +311 -0
  30. package/src/utils/args.js +113 -0
  31. package/src/utils/auth-flow.js +373 -0
  32. package/src/utils/auth.js +90 -0
  33. package/src/utils/calendar.js +23 -0
  34. package/src/utils/collection-ops.js +333 -0
  35. package/src/utils/collection.js +240 -0
  36. package/src/utils/formatters.js +157 -0
  37. package/src/utils/helpers.js +283 -0
  38. package/src/utils/hot.js +182 -0
  39. package/src/utils/install.js +40 -0
  40. package/src/utils/prompts.js +87 -0
  41. package/src/utils/relay.js +74 -0
  42. package/src/utils/status.js +68 -0
  43. package/src/utils/tui-interactive.js +197 -0
  44. package/src/utils/tui-render.js +86 -0
  45. package/src/utils/turnstile-flow.js +154 -0
  46. package/src/utils/validators.js +412 -0
@@ -0,0 +1,3888 @@
1
+ import process from "node:process";
2
+ import { getConfig } from "./config.js";
3
+
4
+ export class CommandError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "CommandError";
8
+ }
9
+ }
10
+
11
+ const SUBJECT_TYPE_LABELS = {
12
+ 1: "Book",
13
+ 2: "Anime",
14
+ 3: "Music",
15
+ 4: "Game",
16
+ 6: "Real",
17
+ };
18
+
19
+ const SUBJECT_TYPE_ORDER = [2, 1, 3, 4, 6];
20
+
21
+ const COLLECTION_STATUS_LABELS = {
22
+ 1: "Wish",
23
+ 2: "Collect",
24
+ 3: "Doing",
25
+ 4: "On hold",
26
+ 5: "Dropped",
27
+ };
28
+
29
+ const EPISODE_TYPE_LABELS = {
30
+ 0: "Main",
31
+ 1: "SP",
32
+ 2: "OP",
33
+ 3: "ED",
34
+ 4: "Trailer",
35
+ 5: "MAD",
36
+ 6: "Other",
37
+ };
38
+
39
+ const EPISODE_COLLECTION_STATUS_LABELS = {
40
+ 0: "Removed",
41
+ 1: "Queue",
42
+ 2: "Watched",
43
+ 3: "Dropped",
44
+ };
45
+
46
+ const GROUP_MEMBER_ROLE_LABELS = {
47
+ [-2]: "Visitor",
48
+ [-1]: "Guest",
49
+ 0: "Member",
50
+ 1: "Creator",
51
+ 2: "Moderator",
52
+ 3: "Blocked",
53
+ };
54
+
55
+ const TIMELINE_CAT_LABELS = {
56
+ 1: "Daily",
57
+ 2: "Wiki",
58
+ 3: "Subject",
59
+ 4: "Progress",
60
+ 5: "Status",
61
+ 6: "Blog",
62
+ 7: "Index",
63
+ 8: "Mono",
64
+ 9: "Doujin",
65
+ };
66
+
67
+ export function printUsage(target) {
68
+ console.log(buildUsageText(target));
69
+ }
70
+
71
+ function buildUsageText(target) {
72
+ const normalized = normalizeUsageTarget(target);
73
+
74
+ switch (normalized) {
75
+ case "auth":
76
+ return buildGroupUsage("Auth", [
77
+ ["bgm auth login [--email <email>] [--password <password>] [--turnstile-token <token>] [--manual] [--force]", "Private session channel: p1 account login, with hidden password prompt when interactive. Refuses to log in twice unless --force is passed."],
78
+ ["bgm [--json] auth login --email <email> --password <password> --turnstile-token <token>", "Private session channel: non-interactive p1 login."],
79
+ ["bgm [--json] auth logout", "Private session channel: call p1 logout and clear the saved session."],
80
+ ["bgm [--json] auth session-status", "Private session channel: show whether a p1 session cookie is saved."],
81
+ ["bgm [--json] auth status", "Show both auth channels without contacting Bangumi."],
82
+ ["bgm [--json] auth clear [--token|--session]", "Clear all auth state, or only one channel when filtered."],
83
+ ["bgm [--json] auth set-token <access_token>", "Access Token channel: save an existing Bangumi access token directly."],
84
+ ["bgm [--json] auth token-status", "Access Token channel: validate the saved access token with Bangumi."],
85
+ ["bgm [--json] auth login-url [--client-id xxx] [--redirect-uri xxx] [--state xxx]", "Access Token channel: generate a Bangumi OAuth authorization URL for manual testing."],
86
+ ["bgm [--json] auth token --code <code> [--save]", "Access Token channel: exchange an OAuth authorization code for access and refresh tokens."],
87
+ ["bgm [--json] auth refresh [--save]", "Access Token channel: refresh the saved OAuth access token with the refresh token."],
88
+ ["bgm [--json] auth turnstile [--manual] [--listen-host <host>] [--port n] [--public-origin <url>] [--timeout-seconds <n>]", "Prefer the hosted official Bangumi Turnstile flow and fall back to the local helper when needed."],
89
+ ["bgm auth session-login [--manual]", "Private session helper: open the official private API login page and save a pasted chiiNextSessionID."],
90
+ ["bgm [--json] auth set-session <chiiNextSessionID|cookie_string>", "Save a private API session cookie value for p1 requests."],
91
+ ]);
92
+ case "config":
93
+ return buildGroupUsage("Config", [
94
+ ["bgm [--json] config show", "Show the effective local runtime config used by the CLI."],
95
+ ["bgm [--json] config set <key> <value>", "Save one config value into the local CLI config file."],
96
+ ["bgm [--json] config unset <key>", "Remove one config value from the local CLI config file."],
97
+ ]);
98
+ case "setup":
99
+ return buildGroupUsage("Setup", [
100
+ ["bgm [--json] --version", "Show CLI version and local config/auth summary."],
101
+ ["bgm --init", "Run the interactive setup wizard for login and local CLI setup."],
102
+ ["bgm [--json] setup install-path", "Add this repository to PATH so you can run bgm globally."],
103
+ ["bgm [--json] setup update", "Download and reinstall the latest managed bgm-cli copy without removing config."],
104
+ ["bgm tui", "Open the interactive TUI for non-login operations."],
105
+ ]);
106
+ case "subject":
107
+ return buildGroupUsage("Subject", [
108
+ ["bgm [--json] subject get <subject_id> [--verbose]", "Fetch one Bangumi subject by subject ID. Add --verbose for infobox, tags, rating distribution, and images."],
109
+ ["bgm [--json] subject list --type <book|anime|music|game|real> [--sort date|rank] [--limit n]", "Browse public Bangumi subjects by type and list filters."],
110
+ ["bgm [--json] subject search <keyword> [--type anime] [--sort match|heat|rank|score] [--tag xxx]", "Search Bangumi subjects by keyword with optional filters."],
111
+ ["bgm [--json] subject comments <subject_id> [--type <wish|collect|doing|on_hold|dropped>] [--limit n] [--offset n]", "List subject interest comments from the private API."],
112
+ ["bgm [--json] subject reviews <subject_id> [--limit n] [--offset n]", "List subject reviews."],
113
+ ["bgm [--json] subject topics <subject_id> [--limit n] [--offset n]", "List discussion topics for one subject."],
114
+ ["bgm [--json] subject recent-topics [--limit n] [--offset n]", "List the latest subject discussion topics across Bangumi."],
115
+ ["bgm [--json] subject topic <topic_id>", "Fetch one subject discussion topic."],
116
+ ["bgm [--json] subject create-topic <subject_id> <title> <content> [--turnstile-token <token>] [--manual]", "Create one subject discussion topic."],
117
+ ["bgm [--json] subject edit-topic <topic_id> <title> <content>", "Edit one of your subject discussion topics."],
118
+ ["bgm [--json] subject reply <topic_id> <content> [--reply-to <post_id>] [--turnstile-token <token>] [--manual]", "Reply to one subject discussion topic."],
119
+ ["bgm [--json] subject post <post_id>", "Fetch one subject discussion reply."],
120
+ ["bgm [--json] subject edit-post|delete-post|unlike-post <post_id>", "Edit, delete, or remove your reaction from one subject discussion reply."],
121
+ ["bgm [--json] subject like-post <post_id> <value>", "React to one subject discussion reply with a supported Bangumi reaction value."],
122
+ ["bgm [--json] subject like-collect <collect_id> <value>", "React to one subject collection comment with a supported Bangumi reaction value."],
123
+ ["bgm [--json] subject unlike-collect <collect_id>", "Remove your reaction from one subject collection comment."],
124
+ ["bgm [--json] subject characters|collects|staff|indexes|relations|recs <subject_id> [--limit n] [--offset n]", "List related subject community resources."],
125
+ ]);
126
+ case "episode":
127
+ case "ep":
128
+ return buildGroupUsage("Episode", [
129
+ ["bgm [--json] episode list <subject_id> [--type <main|sp|op|ed|op_ed|trailer|pv|mad|other>] [--limit n] [--offset n]", "List episodes for one subject. If an access token is saved, the request also carries it for NSFW subjects."],
130
+ ["bgm [--json] episode get <episode_id>", "Fetch one episode by ID."],
131
+ ["bgm [--json] episode comments <episode_id>", "List comments under one episode."],
132
+ ["bgm [--json] episode comments <subject_id> <episode_number> [--type <main|sp|op|ed|op_ed|trailer|pv|mad|other>]", "List comments by resolving an episode number inside one subject."],
133
+ ["bgm [--json] episode comment <episode_id> <content> [--reply-to <comment_id>] [--turnstile-token <token>] [--manual]", "Create one episode comment."],
134
+ ["bgm [--json] episode edit-comment|delete-comment|unlike-comment <comment_id>", "Edit, delete, or remove your reaction from one episode comment."],
135
+ ["bgm [--json] episode like-comment <comment_id> <value>", "React to one episode comment with a supported Bangumi reaction value."],
136
+ ["bgm [--json] episode status <episode_id> <queue|watched|drop|remove>", "Update one episode collection status."],
137
+ ["bgm [--json] episode watch <subject_id> <episode_number>", "Mark one main episode number as watched without looking up the episode ID manually."],
138
+ ], [
139
+ "Notes",
140
+ " NSFW/R18 subjects may require a saved access token.",
141
+ " Bangumi may return a misleading 404 when episode listing is blocked by auth or account eligibility.",
142
+ ]);
143
+ case "collection":
144
+ return buildGroupUsage("Collection", [
145
+ ["bgm [--json] collection list [--user <username>] [--status <wish|collect|doing|on_hold|dropped>] [--type <book|anime|music|game|real>] [--sort <updated|name|rank|community_score|user_score|date>] [--order <asc|desc>] [--limit n] [--offset n]", "List a user's collections, with optional filters and sorting. Defaults to the current user."],
146
+ ["bgm [--json] collection get <subject_id>", "Show the current user's collection detail for one subject."],
147
+ ["bgm [--json] collection collect <subject_id>|--search <keyword> [--status <wish|collect|doing|on_hold|dropped>]", "Create or update one subject collection. Default status is wish."],
148
+ ["bgm [--json] collection comment <subject_id>|--search <keyword> <comment>", "Update one subject collection comment."],
149
+ ["bgm [--json] collection rate <subject_id>|--search <keyword> <0-10>", "Update one subject collection rating. Use 0 to clear rating."],
150
+ ["bgm [--json] collection status <subject_id>|--search <keyword> <wish|collect|doing|on_hold|dropped>", "Update one subject collection watching/reading status."],
151
+ ["bgm [--json] collection characters|persons|indexes [--user <username>] [--limit n] [--offset n]", "List p1 character, person, or index collections for one user. Defaults to the current user."],
152
+ ["bgm [--json] collection collect-character|uncollect-character <character_id>", "Add or remove a character collection for the current user."],
153
+ ["bgm [--json] collection collect-person|uncollect-person <person_id>", "Add or remove a person collection for the current user."],
154
+ ["bgm [--json] collection collect-index|uncollect-index <index_id>", "Add or remove an index collection for the current user."],
155
+ ]);
156
+ case "user":
157
+ return buildGroupUsage("User", [
158
+ ["bgm [--json] user me", "Show the current authenticated user profile."],
159
+ ["bgm [--json] user get <username_or_initial_uid>", "Fetch one public Bangumi user profile by username or numeric ID."],
160
+ ["bgm [--json] user friends [username] [--limit n] [--offset n]", "List one user's friends. Defaults to the current user."],
161
+ ["bgm [--json] user followers [username] [--limit n] [--offset n]", "List one user's followers. Defaults to the current user."],
162
+ ]);
163
+ case "notify":
164
+ return buildGroupUsage("Notify", [
165
+ ["bgm [--json] notify [list] [--limit n] [--unread true|false]", "List notifications from the private API."],
166
+ ["bgm [--json] notify clear [notification_id ...]", "Mark all notifications or selected notifications as read."],
167
+ ]);
168
+ case "group":
169
+ return buildGroupUsage("Group", [
170
+ ["bgm [--json] group list [--mode <all|joined|managed>] [--sort <created|updated|posts|topics|members>] [--limit n] [--offset n]", "List Bangumi groups from the private API."],
171
+ ["bgm [--json] group get <group_name>", "Fetch one Bangumi group by slug."],
172
+ ["bgm [--json] group topics <group_name> [--limit n] [--offset n]", "List topics inside one group."],
173
+ ["bgm [--json] group topic <topic_id> [--reply-limit n]", "Fetch one group topic detail."],
174
+ ["bgm [--json] group create-topic <group_name> <title> <content> [--turnstile-token <token>] [--manual]", "Create one group topic."],
175
+ ["bgm [--json] group reply <topic_id> <content> [--reply-to <reply_id>] [--turnstile-token <token>] [--manual]", "Reply to one group topic."],
176
+ ["bgm [--json] group edit-topic <topic_id> <title> <content>", "Edit one of your group topics."],
177
+ ["bgm [--json] group post <post_id>", "Fetch one group topic reply."],
178
+ ["bgm [--json] group edit-post|delete-post|unlike-post <post_id>", "Edit, delete, or remove your reaction from one group topic reply."],
179
+ ["bgm [--json] group like-post <post_id> <value>", "React to one group topic reply with a supported Bangumi reaction value."],
180
+ ["bgm [--json] group members <group_name> [--role <visitor|guest|member|creator|moderator|blocked>] [--limit n] [--offset n]", "List members of one group."],
181
+ ["bgm [--json] group user [username] [--limit n] [--offset n]", "List groups joined by one user. Defaults to the current user."],
182
+ ["bgm [--json] group recent-topics [--mode <all|joined|created|replied>] [--limit n] [--offset n]", "List the latest group topics across Bangumi."],
183
+ ["bgm [--json] group latest-replies [--mode <all|joined|created|replied>] [--limit n] [--scan n]", "List topics that were recently bumped by replies."],
184
+ ["bgm [--json] group hot [--window <day|week|month>] [--mode <all|joined|created|replied>] [--limit n] [--scan n]", "Rank the hottest groups from recent topic activity."],
185
+ ["bgm [--json] group hot-topics [--window <day|week|month>] [--mode <all|joined|created|replied>] [--limit n] [--scan n]", "Rank the hottest group topics from recent topic activity."],
186
+ ]);
187
+ case "blog":
188
+ return buildGroupUsage("Blog", [
189
+ ["bgm [--json] blog list [--user <username>] [--limit n] [--offset n]", "List one user's blog entries. Defaults to the current user."],
190
+ ["bgm [--json] blog get <blog_id>", "Fetch one Bangumi blog entry by ID."],
191
+ ["bgm [--json] blog comments <blog_id>", "List comments under one blog entry."],
192
+ ["bgm [--json] blog reply <blog_id> <content> [--reply-to <comment_id>] [--turnstile-token <token>] [--manual]", "Experimental: reply to one blog entry or one existing blog comment."],
193
+ ["bgm [--json] blog edit-comment <comment_id> <content>", "Experimental: edit one of your blog comments."],
194
+ ["bgm [--json] blog delete-comment <comment_id>", "Experimental: delete one of your blog comments."],
195
+ ["bgm [--json] blog photos <blog_id> [--limit n] [--offset n]", "List photos attached to one blog entry."],
196
+ ["bgm [--json] blog subjects <blog_id>", "List subjects related to one blog entry."],
197
+ ]);
198
+ case "index":
199
+ return buildGroupUsage("Index", [
200
+ ["bgm [--json] index create <title> <desc> [--private <true|false>]", "Create one index."],
201
+ ["bgm [--json] index get <index_id>", "Fetch one index by ID."],
202
+ ["bgm [--json] index update <index_id> [--title <title>] [--desc <desc>] [--private <true|false>]", "Update one of your indexes."],
203
+ ["bgm [--json] index delete <index_id>", "Delete one of your indexes."],
204
+ ["bgm [--json] index comments <index_id>", "List comments under one index."],
205
+ ["bgm [--json] index comment <index_id> <content> [--reply-to <comment_id>] [--turnstile-token <token>] [--manual]", "Create one index comment."],
206
+ ["bgm [--json] index edit-comment <comment_id> <content>", "Edit one of your index comments."],
207
+ ["bgm [--json] index delete-comment <comment_id>", "Delete one of your index comments."],
208
+ ["bgm [--json] index related <index_id> [--cat <subject|character|person|ep|blog|group_topic|subject_topic>] [--type <book|anime|music|game|real>] [--limit n] [--offset n]", "List related content inside one index."],
209
+ ["bgm [--json] index user [username] [--limit n] [--offset n]", "List indexes created by one user. Defaults to the current user."],
210
+ ["bgm [--json] index add-related <index_id> --cat <subject|character|person|ep|blog|group_topic|subject_topic> --sid <sid> [--order <n>] [--comment <text>] [--award <text>]", "Add one related item to an index."],
211
+ ["bgm [--json] index update-related <index_id> <related_id> --order <n> --comment <text>", "Update one index related item."],
212
+ ["bgm [--json] index delete-related <index_id> <related_id>", "Delete one index related item."],
213
+ ]);
214
+ case "timeline":
215
+ return buildGroupUsage("Timeline", [
216
+ ["bgm [--json] timeline list [--mode <all|friends>] [--limit n] [--until <timeline_id>]", "List timeline entries from the private API."],
217
+ ["bgm [--json] timeline events [--mode <all|friends>] [--cat <daily|wiki|subject|progress|status|blog|index|mono|doujin>] [--limit n] [--timeout-seconds n]", "Sample the p1 SSE timeline event stream with a bounded timeout."],
218
+ ["bgm [--json] timeline user [username] [--limit n] [--until <timeline_id>]", "List timeline entries posted by one user. Defaults to the current user."],
219
+ ["bgm [--json] timeline replies <timeline_id>", "List replies under one timeline entry."],
220
+ ["bgm [--json] timeline say <content> [--turnstile-token <token>] [--manual]", "Create one timeline status."],
221
+ ["bgm [--json] timeline reply <timeline_id> <content> [--reply-to <comment_id>] [--turnstile-token <token>] [--manual]", "Reply to one timeline entry."],
222
+ ["bgm [--json] timeline delete <timeline_id>", "Delete one of your timeline entries."],
223
+ ["bgm [--json] timeline like <timeline_id> <value>", "React to one timeline entry with a supported Bangumi reaction value."],
224
+ ["bgm [--json] timeline unlike <timeline_id>", "Remove your reaction from one timeline entry."],
225
+ ]);
226
+ case "status":
227
+ return buildGroupUsage("Status", [
228
+ ["bgm [--json] status [--site <bgm.tv|bangumi.tv|chii.in>] [--audience <guest|auth|authenticated>]", "Show current service health from the community-run Bangumi status service."],
229
+ ["bgm [--json] status current [--site <bgm.tv|bangumi.tv|chii.in>] [--audience <guest|auth|authenticated>]", "Show current service health explicitly."],
230
+ ["bgm [--json] status incidents [--site <bgm.tv|bangumi.tv|chii.in>] [--audience <guest|auth|authenticated>] [--limit n]", "Show recent incidents only."],
231
+ ]);
232
+ case "calendar":
233
+ return buildGroupUsage("Calendar", [
234
+ ["bgm [--json] calendar [today]", "Show today's anime broadcast schedule (default)."],
235
+ ["bgm [--json] calendar all", "Show the full weekly anime broadcast calendar."],
236
+ ["bgm [--json] calendar <weekday>", "Show schedule for a specific day: monday/mon, tuesday/tue, wednesday/wed, thursday/thu, friday/fri, saturday/sat, sunday/sun."],
237
+ ]);
238
+ case "character":
239
+ return buildGroupUsage("Character", [
240
+ ["bgm [--json] character search <keyword> [--nsfw <true|false>] [--limit n] [--offset n]", "Search Bangumi characters."],
241
+ ["bgm [--json] character get <character_id>", "Fetch one character."],
242
+ ["bgm [--json] character casts|collects|comments|indexes|photos|relations <character_id> [--limit n] [--offset n]", "List related character resources."],
243
+ ["bgm [--json] character photos-preview <character_id> [--limit n]", "List the character homepage photo preview."],
244
+ ["bgm [--json] character photo <character_id> <photo_id>", "Fetch one character photo."],
245
+ ["bgm [--json] character photo-comments <character_id> <photo_id>", "List comments under one character photo."],
246
+ ["bgm [--json] character comment <character_id> <content> [--reply-to <comment_id>] [--turnstile-token <token>] [--manual]", "Create one character comment."],
247
+ ["bgm [--json] character edit-comment <comment_id> <content>", "Edit one of your character comments."],
248
+ ["bgm [--json] character delete-comment <comment_id>", "Delete one of your character comments."],
249
+ ]);
250
+ case "person":
251
+ return buildGroupUsage("Person", [
252
+ ["bgm [--json] person search <keyword> [--career <seiyu,writer,...>] [--limit n] [--offset n]", "Search Bangumi persons."],
253
+ ["bgm [--json] person get <person_id>", "Fetch one person."],
254
+ ["bgm [--json] person casts|collects|comments|indexes|photos|relations|works <person_id> [--limit n] [--offset n]", "List related person resources."],
255
+ ["bgm [--json] person photos-preview <person_id> [--limit n]", "List the person homepage photo preview."],
256
+ ["bgm [--json] person photo <person_id> <photo_id>", "Fetch one person photo."],
257
+ ["bgm [--json] person photo-comments <person_id> <photo_id>", "List comments under one person photo."],
258
+ ["bgm [--json] person comment <person_id> <content> [--reply-to <comment_id>] [--turnstile-token <token>] [--manual]", "Create one person comment."],
259
+ ["bgm [--json] person edit-comment <comment_id> <content>", "Edit one of your person comments."],
260
+ ["bgm [--json] person delete-comment <comment_id>", "Delete one of your person comments."],
261
+ ]);
262
+ case "trending":
263
+ return buildGroupUsage("Trending", [
264
+ ["bgm [--json] trending subjects --type <book|anime|music|game|real> [--limit n] [--offset n]", "List trending subjects."],
265
+ ["bgm [--json] trending subject-topics [--limit n] [--offset n]", "List trending subject discussion topics."],
266
+ ]);
267
+ default:
268
+ return buildMainUsage();
269
+ }
270
+ }
271
+
272
+ function buildMainUsage() {
273
+ return `bgm-cli
274
+
275
+ Usage
276
+ bgm <command> [subcommand] [options]
277
+ bgm <command> --help
278
+
279
+ Core
280
+ bgm --init
281
+ Run the interactive setup wizard for login and local CLI setup.
282
+ bgm [--json] auth set-token <access_token>
283
+ Save an existing Bangumi access token directly.
284
+ bgm [--json] user me
285
+ Show the current authenticated user profile.
286
+ bgm [--json] notify
287
+ List private API notifications.
288
+ bgm [--json] subject search <keyword> [--type anime] [--limit n]
289
+ Search Bangumi subjects by keyword.
290
+ bgm [--json] subject get <subject_id> [--verbose]
291
+ Fetch one Bangumi subject by subject ID. Add --verbose for detailed info.
292
+ bgm [--json] collection get <subject_id>
293
+ Show the current user's collection detail for one subject.
294
+ bgm [--json] collection status <subject_id> <wish|collect|doing|on_hold|dropped>
295
+ Update one subject collection status.
296
+ bgm [--json] episode watch <subject_id> <episode_number>
297
+ Mark one main episode as watched.
298
+ bgm [--json] group list [--limit n]
299
+ List Bangumi groups.
300
+ bgm [--json] status
301
+ Show current Bangumi service health.
302
+
303
+ Commands
304
+ auth Login, token, session, and Turnstile helpers
305
+ config Local runtime config read/write
306
+ setup Init and install-path helpers
307
+ user User profile reads
308
+ notify Private API notifications
309
+ subject Subject reads and search
310
+ collection Subject collection reads and writes
311
+ episode Episode list and progress writes
312
+ group Group reads and writes
313
+ blog Blog reads and comment writes
314
+ index Index reads and writes
315
+ character Character reads and search
316
+ person Person reads and search
317
+ timeline Timeline reads and writes
318
+ trending Trending subject and topic reads
319
+ status Community status service reads
320
+ calendar Weekly anime broadcast calendar
321
+ tui Interactive terminal UI
322
+
323
+ Examples
324
+ bgm subject search "Ghost in the Shell" --type anime --limit 5
325
+ bgm collection status 12 doing
326
+ bgm episode watch 12 1
327
+ bgm group list --limit 10
328
+ bgm notify --limit 10
329
+ bgm blog --help
330
+ bgm episode --help`;
331
+ }
332
+
333
+ function buildGroupUsage(title, commands, extraLines = []) {
334
+ const lines = [`${title} commands`, "", "Usage"];
335
+
336
+ for (const [command, description] of commands) {
337
+ lines.push(` ${command}`);
338
+ lines.push(` ${description}`);
339
+ }
340
+
341
+ lines.push("");
342
+ lines.push("Tip");
343
+ lines.push(" Add `--json` for machine-readable output.");
344
+
345
+ if (Array.isArray(extraLines) && extraLines.length > 0) {
346
+ lines.push("");
347
+ lines.push(...extraLines);
348
+ }
349
+
350
+ return lines.join("\n");
351
+ }
352
+
353
+ function normalizeUsageTarget(target) {
354
+ if (!target) {
355
+ return "";
356
+ }
357
+
358
+ return String(target).toLowerCase();
359
+ }
360
+
361
+ export function printResult(value, context = {}) {
362
+ if (context.json) {
363
+ console.log(JSON.stringify(value, null, 2));
364
+ return;
365
+ }
366
+
367
+ console.log(formatDisplayResult(value, context));
368
+ }
369
+
370
+ export function formatDisplayResult(value, context = {}) {
371
+ if (value === null || value === undefined) {
372
+ return String(value);
373
+ }
374
+
375
+ if (typeof value === "string") {
376
+ return value;
377
+ }
378
+
379
+ if (isConfigShowPayload(value)) {
380
+ return formatConfigShow(value);
381
+ }
382
+
383
+ if (isConfigMutationPayload(value)) {
384
+ return formatConfigMutation(value);
385
+ }
386
+
387
+ if (isProxyShowPayload(value)) {
388
+ return formatProxyShow(value);
389
+ }
390
+
391
+ if (isVersionStatusPayload(value)) {
392
+ return formatVersionStatus(value);
393
+ }
394
+
395
+ if (isInstallPathPayload(value)) {
396
+ return formatInstallPath(value);
397
+ }
398
+
399
+ if (isLoginUrlPayload(value)) {
400
+ return `Authorization URL\n${value.loginUrl}`;
401
+ }
402
+
403
+ if (isTokenSetPayload(value)) {
404
+ return [
405
+ "Access token saved",
406
+ `Config file: ${value.configFile}`,
407
+ `Token: ${value.accessTokenPreview}`,
408
+ ].join("\n");
409
+ }
410
+
411
+ if (isAuthStatusPayload(value)) {
412
+ return formatAuthStatus(value);
413
+ }
414
+
415
+ if (isTokenStatusPayload(value)) {
416
+ return formatTokenStatus(value);
417
+ }
418
+
419
+ if (isPrivateSessionMutationPayload(value)) {
420
+ return formatPrivateSessionMutation(value);
421
+ }
422
+
423
+ if (isPrivateSessionStatusPayload(value)) {
424
+ return formatPrivateSessionStatus(value);
425
+ }
426
+
427
+ if (isAuthLoginPayload(value)) {
428
+ return formatAuthLogin(value);
429
+ }
430
+
431
+ if (isAuthLogoutPayload(value)) {
432
+ return formatAuthLogout(value);
433
+ }
434
+
435
+ if (isAuthClearPayload(value)) {
436
+ return formatAuthClear(value);
437
+ }
438
+
439
+ if (isBlogListPayload(value)) {
440
+ return formatBlogList(value);
441
+ }
442
+
443
+ if (isBlogCommentsPayload(value)) {
444
+ return formatBlogComments(value);
445
+ }
446
+
447
+ if (isBlogPhotosPayload(value)) {
448
+ return formatBlogPhotos(value);
449
+ }
450
+
451
+ if (isBlogSubjectsPayload(value)) {
452
+ return formatBlogSubjects(value);
453
+ }
454
+
455
+ if (isBlogCommentMutationPayload(value)) {
456
+ return formatBlogCommentMutation(value);
457
+ }
458
+
459
+ if (isBlogPayload(value)) {
460
+ return formatBlog(value);
461
+ }
462
+
463
+ if (isIndexCommentsPayload(value)) {
464
+ return formatIndexComments(value);
465
+ }
466
+
467
+ if (isIndexRelatedPayload(value)) {
468
+ return formatIndexRelated(value);
469
+ }
470
+
471
+ if (isIndexMutationPayload(value)) {
472
+ return formatIndexMutation(value);
473
+ }
474
+
475
+ if (isIndexCommentMutationPayload(value)) {
476
+ return formatIndexCommentMutation(value);
477
+ }
478
+
479
+ if (isIndexRelatedMutationPayload(value)) {
480
+ return formatIndexRelatedMutation(value);
481
+ }
482
+
483
+ if (isIndexPayload(value)) {
484
+ return formatIndex(value);
485
+ }
486
+
487
+ if (isTimelineListPayload(value)) {
488
+ return formatTimelineList(value);
489
+ }
490
+
491
+ if (isTimelineEventsPayload(value)) {
492
+ return formatTimelineEvents(value);
493
+ }
494
+
495
+ if (isTimelineRepliesPayload(value)) {
496
+ return formatTimelineReplies(value);
497
+ }
498
+
499
+ if (isTimelineMutationPayload(value)) {
500
+ return formatTimelineMutation(value);
501
+ }
502
+
503
+ if (isStatusIncidentsPayload(value)) {
504
+ return formatStatusIncidents(value);
505
+ }
506
+
507
+ if (isStatusCurrentPayload(value)) {
508
+ return formatStatusCurrent(value);
509
+ }
510
+
511
+ if (isNotificationListPayload(value)) {
512
+ return formatNotificationList(value);
513
+ }
514
+
515
+ if (isNotificationClearPayload(value)) {
516
+ return formatNotificationClear(value);
517
+ }
518
+
519
+ if (isCollectionListPayload(value)) {
520
+ return formatCollectionList(value);
521
+ }
522
+
523
+ if (isCollectionMutationPayload(value)) {
524
+ return formatCollectionMutation(value);
525
+ }
526
+
527
+ if (isEpisodeListPayload(value)) {
528
+ return formatEpisodeList(value);
529
+ }
530
+
531
+ if (isEpisodeCommentsPayload(value)) {
532
+ return formatEpisodeComments(value);
533
+ }
534
+
535
+ if (isEpisodeMutationPayload(value)) {
536
+ return formatEpisodeMutation(value);
537
+ }
538
+
539
+ if (isEpisodeCommentMutationPayload(value)) {
540
+ return formatEpisodeCommentMutation(value);
541
+ }
542
+
543
+ if (isGroupListPayload(value)) {
544
+ return formatGroupList(value);
545
+ }
546
+
547
+ if (isGroupHotPayload(value)) {
548
+ return formatGroupHot(value);
549
+ }
550
+
551
+ if (isGroupHotTopicsPayload(value)) {
552
+ return formatGroupHotTopics(value);
553
+ }
554
+
555
+ if (isGroupLatestRepliesPayload(value)) {
556
+ return formatGroupLatestReplies(value);
557
+ }
558
+
559
+ if (isGroupMembersPayload(value)) {
560
+ return formatGroupMembers(value);
561
+ }
562
+
563
+ if (isGroupTopicsPayload(value)) {
564
+ return formatGroupTopics(value);
565
+ }
566
+
567
+ if (isGroupPayload(value)) {
568
+ return formatGroup(value);
569
+ }
570
+
571
+ if (isGroupTopicPayload(value)) {
572
+ return formatGroupTopic(value);
573
+ }
574
+
575
+ if (isSubjectTopicPayload(value)) {
576
+ return formatSubjectTopic(value);
577
+ }
578
+
579
+ if (isGroupTopicMutationPayload(value)) {
580
+ return formatGroupTopicMutation(value);
581
+ }
582
+
583
+ if (isTopicMutationPayload(value)) {
584
+ return formatTopicMutation(value);
585
+ }
586
+
587
+ if (isTopicPostPayload(value)) {
588
+ return formatTopicPost(value);
589
+ }
590
+
591
+ if (isPostMutationPayload(value)) {
592
+ return formatPostMutation(value);
593
+ }
594
+
595
+ if (isSubjectCollectMutationPayload(value)) {
596
+ return formatSubjectCollectMutation(value);
597
+ }
598
+
599
+ if (isMonoCommentMutationPayload(value)) {
600
+ return formatMonoCommentMutation(value);
601
+ }
602
+
603
+ if (isMonoPhotoPayload(value)) {
604
+ return formatMonoPhoto(value);
605
+ }
606
+
607
+ if (isMonoPhotoCommentsPayload(value)) {
608
+ return formatMonoPhotoComments(value);
609
+ }
610
+
611
+ if (isSimpleCollectionMutationPayload(value)) {
612
+ return formatSimpleCollectionMutation(value);
613
+ }
614
+
615
+ if (isTurnstileTokenPayload(value)) {
616
+ return formatTurnstileToken(value);
617
+ }
618
+
619
+ if (isOAuthTokenPayload(value)) {
620
+ return formatOAuthToken(value);
621
+ }
622
+
623
+ if (isMonoDetailPayload(value)) {
624
+ return formatMonoDetail(value);
625
+ }
626
+
627
+ if (isGenericP1ListPayload(value)) {
628
+ return formatGenericP1List(value);
629
+ }
630
+
631
+ if (isPagedSubjectPayload(value)) {
632
+ return formatPagedSubjects(value);
633
+ }
634
+
635
+ if (isSubjectPayload(value)) {
636
+ return formatSubject(value, context);
637
+ }
638
+
639
+ if (isUserPayload(value)) {
640
+ return formatUser(value, context);
641
+ }
642
+
643
+ if (isCalendarPayload(value)) {
644
+ return formatCalendar(value);
645
+ }
646
+
647
+ return JSON.stringify(value, null, 2);
648
+ }
649
+
650
+ function formatConfigShow(payload) {
651
+ const lines = ["Config", ` File: ${payload.configFile}`];
652
+ if (payload.configSourceFile && payload.configSourceFile !== payload.configFile) {
653
+ lines.push(` Loaded from: ${payload.configSourceFile}`);
654
+ }
655
+ const config = payload.config ?? {};
656
+ const entries = Object.entries(config);
657
+
658
+ if (entries.length === 0) {
659
+ lines.push(" Values: empty");
660
+ } else {
661
+ lines.push(" Values:");
662
+ for (const [key, rawValue] of entries) {
663
+ lines.push(` ${key}: ${formatConfigValue(key, rawValue)}`);
664
+ }
665
+ }
666
+
667
+ if (payload.effectiveProxy) {
668
+ const { url, source, active } = payload.effectiveProxy;
669
+ if (url) {
670
+ lines.push(` Proxy: ${formatProxyUrl(url)} (source: ${source}, active: ${active ? "yes" : "no"})`);
671
+ } else {
672
+ lines.push(" Proxy: not set");
673
+ }
674
+ }
675
+
676
+ return lines.join("\n");
677
+ }
678
+
679
+ function formatInstallPath(payload) {
680
+ if (payload.action === "update") {
681
+ return [
682
+ "bgm-cli updated",
683
+ ` Platform: ${payload.platform}`,
684
+ ` Install dir: ${payload.installDir ?? payload.repoDir}`,
685
+ ` Active config file: ${payload.configFile}`,
686
+ "",
687
+ payload.output,
688
+ "",
689
+ payload.shellHint,
690
+ ].join("\n");
691
+ }
692
+
693
+ const lines = [
694
+ "Global command setup completed",
695
+ ` Platform: ${payload.platform}`,
696
+ ` Repository: ${payload.repoDir}`,
697
+ ` Active config file: ${payload.configFile}`,
698
+ "",
699
+ ];
700
+
701
+ if (payload.migratedConfig) {
702
+ lines.push("Existing project config was migrated to the global config file.");
703
+ lines.push("");
704
+ }
705
+
706
+ lines.push(payload.output);
707
+ lines.push("");
708
+ lines.push(payload.shellHint);
709
+ return lines.join("\n");
710
+ }
711
+
712
+ function formatConfigMutation(payload) {
713
+ if (payload.updated) {
714
+ return [
715
+ "Config updated",
716
+ ` Key: ${payload.updated}`,
717
+ ` Value: ${formatConfigValue(payload.updated, payload.value)}`,
718
+ ` Config file: ${payload.configFile}`,
719
+ ].join("\n");
720
+ }
721
+
722
+ if (payload.removed) {
723
+ return [
724
+ "Config removed",
725
+ ` Key: ${payload.removed}`,
726
+ ` Config file: ${payload.configFile}`,
727
+ ].join("\n");
728
+ }
729
+
730
+ return JSON.stringify(payload, null, 2);
731
+ }
732
+
733
+ function formatVersionStatus(payload) {
734
+ return [
735
+ `${payload.name ?? "bgm-cli"} ${payload.version ?? "-"}`,
736
+ ` Config scope: ${payload.configScope ?? "-"}`,
737
+ ` Config file: ${payload.configFile ?? "-"}`,
738
+ payload.configSourceFile && payload.configSourceFile !== payload.configFile
739
+ ? ` Config source: ${payload.configSourceFile}`
740
+ : null,
741
+ ` Access token: ${payload.accessTokenSaved ? "Saved" : "Not saved"}`,
742
+ ` Refresh token: ${payload.refreshTokenSaved ? "Saved" : "Not saved"}`,
743
+ ` Private session: ${payload.privateSessionSaved ? "Saved" : "Not saved"}`,
744
+ ` OAuth app: ${payload.oauthAppConfigured ? "Configured" : "Not configured"}`,
745
+ ` OAuth backend: ${payload.oauthServerBaseUrl ?? "-"}`,
746
+ ` Timezone: ${payload.timezone ?? "-"}`,
747
+ ` User-Agent: ${payload.userAgent ?? "-"}`,
748
+ ].filter(Boolean).join("\n");
749
+ }
750
+
751
+ function formatAuthStatus(payload) {
752
+ const accessToken = payload.channels?.accessToken ?? {};
753
+ const privateSession = payload.channels?.privateSession ?? {};
754
+ return [
755
+ "Auth status",
756
+ ` Config file: ${payload.configFile ?? "-"}`,
757
+ payload.policy ? ` Policy: ${payload.policy}` : null,
758
+ "",
759
+ "Access Token channel",
760
+ ` Saved: ${accessToken.saved ? "Yes" : "No"}`,
761
+ ` Token: ${accessToken.tokenPreview ?? "-"}`,
762
+ ` Refresh token: ${accessToken.refreshTokenSaved ? "Saved" : "Not saved"}`,
763
+ ` Validate: ${accessToken.statusCommand ?? "bgm auth token-status"}`,
764
+ ` Set: ${accessToken.setCommand ?? "bgm auth set-token <access_token>"}`,
765
+ "",
766
+ "Private session channel",
767
+ ` Saved: ${privateSession.saved ? "Yes" : "No"}`,
768
+ ` Session: ${privateSession.sessionPreview ?? "-"}`,
769
+ ` Updated at: ${formatTimestamp(privateSession.updatedAt)}`,
770
+ ` Login: ${privateSession.loginCommand ?? "bgm auth login"}`,
771
+ ` Logout: ${privateSession.logoutCommand ?? "bgm auth logout"}`,
772
+ ].filter((line) => line !== null).join("\n");
773
+ }
774
+
775
+ function formatTokenStatus(payload) {
776
+ if (payload.resource === "access-token-status") {
777
+ return [
778
+ "Access token status",
779
+ ` Valid: ${payload.valid ? "Yes" : "No"}`,
780
+ ` Access token: ${maskToken(payload.accessToken)}`,
781
+ payload.user ? ` User ID: ${payload.user.id ?? "-"}` : null,
782
+ payload.user ? ` Username: ${payload.user.username ?? "-"}` : null,
783
+ payload.user ? ` Nickname: ${payload.user.nickname ?? "-"}` : null,
784
+ payload.error ? ` Error: ${payload.error}` : null,
785
+ ].filter(Boolean).join("\n");
786
+ }
787
+
788
+ return [
789
+ "Access token status",
790
+ ` User ID: ${payload.user_id ?? "-"}`,
791
+ ` Client ID: ${payload.client_id ?? "-"}`,
792
+ ` Expires: ${formatTimestamp(payload.expires)}`,
793
+ ` Scope: ${payload.scope ?? "-"}`,
794
+ ` Access token: ${maskToken(payload.access_token)}`,
795
+ ].join("\n");
796
+ }
797
+
798
+ function formatOAuthToken(payload) {
799
+ return [
800
+ "OAuth token",
801
+ ` Access token: ${maskToken(payload.access_token)}`,
802
+ ` Refresh token: ${maskToken(payload.refresh_token)}`,
803
+ ` Token type: ${payload.token_type ?? "-"}`,
804
+ ` Expires in: ${payload.expires_in ? `${payload.expires_in}s` : "-"}`,
805
+ ` User ID: ${payload.user_id ?? "-"}`,
806
+ ` Scope: ${payload.scope ?? "-"}`,
807
+ ].join("\n");
808
+ }
809
+
810
+ function formatPrivateSessionMutation(payload) {
811
+ return [
812
+ "Private API session saved",
813
+ ` Session: ${payload.sessionPreview}`,
814
+ ` Config file: ${payload.configFile}`,
815
+ " Purpose: optional next.bgm.tv/p1 session support only",
816
+ payload.loginUrl ? ` Login URL: ${payload.loginUrl}` : null,
817
+ ].filter(Boolean).join("\n");
818
+ }
819
+
820
+ function formatPrivateSessionStatus(payload) {
821
+ return [
822
+ "Private API session status",
823
+ ` Saved: ${payload.saved ? "Yes" : "No"}`,
824
+ ` Session: ${payload.sessionPreview ?? "-"}`,
825
+ ` Updated at: ${formatTimestamp(payload.updatedAt)}`,
826
+ " Purpose: optional next.bgm.tv/p1 session support only",
827
+ payload.loginUrl ? ` Login URL: ${payload.loginUrl}` : null,
828
+ ].filter(Boolean).join("\n");
829
+ }
830
+
831
+ function formatAuthLogin(payload) {
832
+ const user = payload.user ?? {};
833
+ return [
834
+ "Private API login completed",
835
+ ` Session saved: ${payload.saved ? "Yes" : "No"}`,
836
+ ` Session: ${payload.sessionPreview ?? "-"}`,
837
+ ` Config file: ${payload.configFile ?? "-"}`,
838
+ ` User: ${formatUserLabel(user, user.id)}`,
839
+ ].join("\n");
840
+ }
841
+
842
+ function formatAuthLogout(payload) {
843
+ return [
844
+ "Private API logout completed",
845
+ ` Session cleared: ${payload.clearedSession ? "Yes" : "No"}`,
846
+ ` Config file: ${payload.configFile ?? "-"}`,
847
+ ].join("\n");
848
+ }
849
+
850
+ function formatAuthClear(payload) {
851
+ return [
852
+ "Auth config cleared",
853
+ ` Config file: ${payload.configFile}`,
854
+ ` Cleared: ${Array.isArray(payload.cleared) ? payload.cleared.join(", ") : "-"}`,
855
+ " Preserved: oauthServerBaseUrl, app metadata, timezone, and other non-auth config",
856
+ ].join("\n");
857
+ }
858
+
859
+ function formatStatusIncidents(payload) {
860
+ const lines = [
861
+ "Bangumi status incidents",
862
+ ` Source: ${payload.source ?? "-"}`,
863
+ ` Feed: ${payload.feedUrl ?? "-"}`,
864
+ ` Feed updated: ${formatTimestamp(payload.feedUpdatedAt)}`,
865
+ ` Showing: ${payload.data?.length ?? 0} of ${payload.total ?? 0}`,
866
+ ];
867
+
868
+ if (payload.filters?.site) {
869
+ lines.push(` Site filter: ${payload.filters.site}`);
870
+ }
871
+ if (payload.filters?.audience) {
872
+ lines.push(` Audience filter: ${payload.filters.audience}`);
873
+ }
874
+
875
+ const incidents = Array.isArray(payload.data) ? payload.data : [];
876
+ lines.push("");
877
+ lines.push("Recent incidents");
878
+ if (incidents.length === 0) {
879
+ lines.push("No incidents matched the current filters.");
880
+ return lines.join("\n");
881
+ }
882
+
883
+ for (const incident of incidents) {
884
+ lines.push("");
885
+ lines.push(`${incident.severity ?? "Incident"} | ${incident.site ?? "-"} | ${incident.audience ?? "-"}`);
886
+ lines.push(` Date: ${incident.date ?? "-"}`);
887
+ lines.push(` Updated: ${formatTimestamp(incident.updatedAt)}`);
888
+ if (incident.summary) {
889
+ lines.push(` Summary: ${incident.summary}`);
890
+ }
891
+ if (incident.link) {
892
+ lines.push(` Link: ${incident.link}`);
893
+ }
894
+ }
895
+
896
+ return lines.join("\n");
897
+ }
898
+
899
+ function formatStatusCurrent(payload) {
900
+ const lines = [
901
+ "Bangumi current status",
902
+ ` Source: ${payload.source ?? "-"}`,
903
+ ` Current status: ${formatCurrentStatusLabel(payload.status)}`,
904
+ ` Monitored: ${payload.monitored ?? 0}`,
905
+ ` Affected now: ${payload.affected ?? 0}`,
906
+ ` Updated: ${formatTimestamp(payload.updatedAt)}`,
907
+ ];
908
+
909
+ if (payload.upstreamMessage) {
910
+ lines.push(` Summary: ${payload.upstreamMessage}`);
911
+ }
912
+ if (payload.filters?.site) {
913
+ lines.push(` Site filter: ${payload.filters.site}`);
914
+ }
915
+ if (payload.filters?.audience) {
916
+ lines.push(` Audience filter: ${payload.filters.audience}`);
917
+ }
918
+
919
+ const affectedComponents = Array.isArray(payload.affectedComponents) ? payload.affectedComponents : [];
920
+ lines.push("");
921
+ lines.push("Affected services now");
922
+ if (affectedComponents.length === 0) {
923
+ lines.push(" None. No monitored service is currently marked as degraded or down in the selected scope.");
924
+ } else {
925
+ for (const component of affectedComponents) {
926
+ lines.push(
927
+ ` - ${component.label ?? "-"} | ${formatCurrentStatusLabel(component.status)} | last check ${formatTimestamp(component.lastCheck)}`,
928
+ );
929
+ }
930
+ }
931
+
932
+ const unresolvedIncidents = Array.isArray(payload.unresolvedIncidents) ? payload.unresolvedIncidents : [];
933
+ if (unresolvedIncidents.length > 0) {
934
+ lines.push("");
935
+ lines.push("Unresolved incidents now");
936
+ for (const incident of unresolvedIncidents) {
937
+ lines.push(
938
+ ` - ${incident.label ?? "-"} | ${formatCurrentStatusLabel(incident.status)} | since ${formatTimestamp(incident.startTs)}`,
939
+ );
940
+ }
941
+ }
942
+
943
+ return lines.join("\n");
944
+ }
945
+
946
+ function formatNotificationList(payload) {
947
+ const notices = Array.isArray(payload.data) ? payload.data : [];
948
+ const lines = [
949
+ "Notifications",
950
+ ` Returned: ${notices.length}`,
951
+ ` Total: ${payload.total ?? notices.length}`,
952
+ ];
953
+
954
+ if (payload.filters?.limit !== undefined) {
955
+ lines.push(` Limit: ${payload.filters.limit}`);
956
+ }
957
+ if (payload.filters?.unread !== undefined) {
958
+ lines.push(` Unread filter: ${payload.filters.unread ? "yes" : "no"}`);
959
+ }
960
+
961
+ if (notices.length === 0) {
962
+ lines.push("No notifications.");
963
+ return lines.join("\n");
964
+ }
965
+
966
+ const rows = notices.map((notice) => ({
967
+ id: notice.id ?? "-",
968
+ unread: notice.unread ? "yes" : "no",
969
+ type: String(notice.type ?? ""),
970
+ title: formatNotificationTitle(notice),
971
+ sender: formatUserLabel(notice.sender),
972
+ created: notice.createdAt ? formatTimestamp(notice.createdAt).split(" ")[0] : "",
973
+ }));
974
+
975
+ lines.push("");
976
+ lines.push(formatTable(rows, [
977
+ { key: "id", header: "#", minWidth: 6, align: "right" },
978
+ { key: "unread", header: "Unread", minWidth: 6, align: "left" },
979
+ { key: "type", header: "Type", minWidth: 4, align: "right" },
980
+ { key: "title", header: "Title", minWidth: 14, maxWidth: 42, align: "left" },
981
+ { key: "sender", header: "Sender", minWidth: 10, maxWidth: 20, align: "left" },
982
+ { key: "created", header: "Created", minWidth: 10, align: "left" },
983
+ ]));
984
+
985
+ return lines.join("\n");
986
+ }
987
+
988
+ function formatNotificationTitle(notice) {
989
+ switch (notice.type) {
990
+ case 14:
991
+ return "请求与你成为好友";
992
+ case 15:
993
+ return "通过了你的好友请求";
994
+ default:
995
+ return notice.title ?? "";
996
+ }
997
+ }
998
+
999
+ function formatNotificationClear(payload) {
1000
+ return [
1001
+ "Notifications marked read",
1002
+ ` Scope: ${payload.cleared === "all" ? "all" : "selected"}`,
1003
+ payload.ids?.length > 0 ? ` IDs: ${payload.ids.join(", ")}` : null,
1004
+ ].filter(Boolean).join("\n");
1005
+ }
1006
+
1007
+ function formatCurrentStatusLabel(value) {
1008
+ switch (value) {
1009
+ case "ok":
1010
+ return colorizeStatusLabel("Operational", "ok");
1011
+ case "degraded":
1012
+ return colorizeStatusLabel("Degraded", "degraded");
1013
+ case "down":
1014
+ return colorizeStatusLabel("Outage", "down");
1015
+ default:
1016
+ return String(value ?? "-");
1017
+ }
1018
+ }
1019
+
1020
+ function colorizeStatusLabel(label, status) {
1021
+ if (!shouldUseColor()) {
1022
+ return label;
1023
+ }
1024
+
1025
+ const colors = {
1026
+ ok: "\u001b[32m",
1027
+ degraded: "\u001b[33m",
1028
+ down: "\u001b[31m",
1029
+ };
1030
+ const color = colors[status];
1031
+ if (!color) {
1032
+ return label;
1033
+ }
1034
+
1035
+ return `${color}${label}\u001b[0m`;
1036
+ }
1037
+
1038
+ function shouldUseColor() {
1039
+ if (!process.stdout.isTTY) {
1040
+ return false;
1041
+ }
1042
+ if (process.env.NO_COLOR) {
1043
+ return false;
1044
+ }
1045
+ if (process.env.FORCE_COLOR === "0") {
1046
+ return false;
1047
+ }
1048
+ return true;
1049
+ }
1050
+
1051
+ function formatCollectionList(payload) {
1052
+ const lines = [];
1053
+ const items = Array.isArray(payload.data) ? payload.data : [];
1054
+ const filters = payload.filters ?? {};
1055
+
1056
+ lines.push("Collections");
1057
+ lines.push(` Total: ${items.length}`);
1058
+ if (filters.user) {
1059
+ lines.push(` User: ${filters.user}`);
1060
+ }
1061
+ lines.push(` Sort: ${filters.sort ?? "updated"} / ${filters.order ?? "desc"}`);
1062
+
1063
+ if (Array.isArray(filters.status) && filters.status.length > 0) {
1064
+ lines.push(` Status filter: ${filters.status.map((value) => formatCollectionStatus(value)).join(", ")}`);
1065
+ } else {
1066
+ lines.push(" Status filter: All");
1067
+ }
1068
+
1069
+ if (Array.isArray(filters.subjectType) && filters.subjectType.length > 0) {
1070
+ lines.push(` Type filter: ${filters.subjectType.map((value) => formatSubjectType(value)).join(", ")}`);
1071
+ } else {
1072
+ lines.push(" Type filter: All");
1073
+ }
1074
+
1075
+ if (items.length === 0) {
1076
+ lines.push("");
1077
+ lines.push("No matching collections.");
1078
+ return lines.join("\n");
1079
+ }
1080
+
1081
+ const rows = items.map((item) => {
1082
+ const subject = item.subject ?? {};
1083
+ return {
1084
+ id: item.subject_id ?? subject.id ?? "-",
1085
+ name: subject.name_cn || subject.name || "-",
1086
+ type: formatSubjectType(item.subject_type ?? subject.type),
1087
+ status: formatCollectionStatus(item.type),
1088
+ my: item.rate ? String(item.rate) : "",
1089
+ score: subject.score !== undefined ? String(subject.score) : "",
1090
+ rank: subject.rank ? `#${subject.rank}` : "",
1091
+ date: subject.date ?? "",
1092
+ };
1093
+ });
1094
+
1095
+ const table = formatTable(rows, [
1096
+ { key: "id", header: "#", minWidth: 5, align: "right" },
1097
+ { key: "name", header: "Name", minWidth: 8, maxWidth: 32, align: "left" },
1098
+ { key: "type", header: "Type", minWidth: 5, align: "left" },
1099
+ { key: "status", header: "Status", minWidth: 7, align: "left" },
1100
+ { key: "my", header: "My", minWidth: 3, align: "right" },
1101
+ { key: "score", header: "Score", minWidth: 5, align: "right" },
1102
+ { key: "rank", header: "Rank", minWidth: 5, align: "right" },
1103
+ { key: "date", header: "Date", minWidth: 10, align: "left" },
1104
+ ]);
1105
+
1106
+ lines.push("");
1107
+ lines.push(table);
1108
+
1109
+ return lines.join("\n");
1110
+ }
1111
+
1112
+ function formatCollectionMutation(payload) {
1113
+ const lines = [];
1114
+ const action = payload.actionLabel ?? payload.action ?? "Collection action";
1115
+ const collection = payload.collection ?? null;
1116
+ const subject = collection?.subject ?? payload.subject ?? {};
1117
+
1118
+ lines.push(action);
1119
+ lines.push(` Subject: #${payload.subjectId ?? collection?.subject_id ?? subject?.id ?? "-"}`);
1120
+ lines.push(` Name: ${subject?.name_cn || subject?.name || payload.subjectName || "-"}`);
1121
+
1122
+ if (subject?.name && subject?.name_cn && subject.name !== subject.name_cn) {
1123
+ lines.push(` Original name: ${subject.name}`);
1124
+ }
1125
+
1126
+ if (collection) {
1127
+ lines.push(` Type: ${formatSubjectType(collection.subject_type ?? subject?.type)}`);
1128
+ lines.push(` Status: ${formatCollectionStatus(collection.type)}`);
1129
+ lines.push(` My rating: ${collection.rate ?? 0}`);
1130
+ lines.push(` Private: ${collection.private ? "Yes" : "No"}`);
1131
+ if (collection.comment) {
1132
+ lines.push(` Comment: ${collection.comment}`);
1133
+ }
1134
+ if (Array.isArray(collection.tags) && collection.tags.length > 0) {
1135
+ lines.push(` Tags: ${collection.tags.join(", ")}`);
1136
+ }
1137
+ if (collection.ep_status !== undefined) {
1138
+ lines.push(` Episode progress: ${collection.ep_status}`);
1139
+ }
1140
+ if (collection.vol_status !== undefined) {
1141
+ lines.push(` Volume progress: ${collection.vol_status}`);
1142
+ }
1143
+ if (collection.updated_at) {
1144
+ lines.push(` Updated at: ${collection.updated_at}`);
1145
+ }
1146
+ }
1147
+
1148
+ return lines.join("\n");
1149
+ }
1150
+
1151
+ function formatEpisodeList(payload) {
1152
+ const lines = [
1153
+ `Episodes: #${payload.subjectId ?? "-"}`,
1154
+ ` Range: ${formatPageRange(payload.offset ?? payload.filters?.offset, payload.data?.length, payload.total)}`,
1155
+ ];
1156
+ const episodes = Array.isArray(payload.data) ? payload.data : [];
1157
+
1158
+ if (payload.filters?.type !== undefined) {
1159
+ lines.push(` Type filter: ${formatEpisodeTypeFilter(payload.filters.type)}`);
1160
+ }
1161
+
1162
+ if (episodes.length === 0) {
1163
+ lines.push("No episodes found.");
1164
+ return lines.join("\n");
1165
+ }
1166
+
1167
+ for (const episode of episodes) {
1168
+ const pieces = [
1169
+ `#${episode.id ?? "-"}`,
1170
+ `[${formatEpisodeType(episode.type)}]`,
1171
+ formatEpisodeNumber(episode),
1172
+ episode.name_cn || episode.name || "-",
1173
+ ].filter(Boolean);
1174
+
1175
+ if (episode.name && episode.name_cn && episode.name !== episode.name_cn) {
1176
+ pieces.push(`(${episode.name})`);
1177
+ }
1178
+ if (episode.airdate) {
1179
+ pieces.push(episode.airdate);
1180
+ }
1181
+ if (episode.duration) {
1182
+ pieces.push(episode.duration);
1183
+ }
1184
+ if (episode.comment !== undefined) {
1185
+ pieces.push(`${episode.comment} comments`);
1186
+ }
1187
+
1188
+ lines.push("");
1189
+ lines.push(`• ${pieces.join(" ")}`);
1190
+ if (episode.desc) {
1191
+ lines.push(` ${truncateText(episode.desc.trim(), 240)}`);
1192
+ }
1193
+ }
1194
+
1195
+ return lines.join("\n");
1196
+ }
1197
+
1198
+ function formatEpisodeMutation(payload) {
1199
+ const lines = [];
1200
+ const episode = payload.collection?.episode ?? payload.episode ?? {};
1201
+
1202
+ lines.push(payload.actionLabel ?? "Episode updated");
1203
+ lines.push(` Episode: #${payload.episodeId ?? episode.id ?? "-"}`);
1204
+ if (payload.subjectId || episode.subject_id) {
1205
+ lines.push(` Subject: #${payload.subjectId ?? episode.subject_id ?? "-"}`);
1206
+ }
1207
+ lines.push(` Type: ${formatEpisodeType(episode.type)}`);
1208
+ lines.push(` Number: ${formatEpisodeNumber(episode) || "-"}`);
1209
+ lines.push(` Name: ${episode.name_cn || episode.name || "-"}`);
1210
+ lines.push(` Status: ${formatEpisodeCollectionStatus(payload.collection?.type ?? payload.status)}`);
1211
+ if (payload.collection?.updated_at) {
1212
+ lines.push(` Updated at: ${formatTimestamp(payload.collection.updated_at)}`);
1213
+ }
1214
+ if (episode.airdate) {
1215
+ lines.push(` Airdate: ${episode.airdate}`);
1216
+ }
1217
+
1218
+ return lines.join("\n");
1219
+ }
1220
+
1221
+ function formatEpisodeComments(payload) {
1222
+ const lines = [
1223
+ `Episode comments: #${payload.episodeId ?? "-"}`,
1224
+ ];
1225
+ if (payload.subjectId !== undefined) {
1226
+ lines.push(` Subject: #${payload.subjectId}`);
1227
+ }
1228
+ if (payload.episodeNumber !== undefined) {
1229
+ lines.push(` Number: ${payload.episodeNumber}`);
1230
+ }
1231
+ if (payload.filters?.type !== undefined) {
1232
+ lines.push(` Type: ${formatEpisodeTypeFilter(payload.filters.type)}`);
1233
+ }
1234
+ lines.push(` Count: ${payload.data?.length ?? 0}`);
1235
+ appendCommentTree(lines, payload.data, "No comments.");
1236
+ return lines.join("\n");
1237
+ }
1238
+
1239
+ function formatEpisodeCommentMutation(payload) {
1240
+ const actionLabels = {
1241
+ create: "created",
1242
+ edit: "updated",
1243
+ delete: "deleted",
1244
+ like: "liked",
1245
+ unlike: "unliked",
1246
+ };
1247
+
1248
+ return [
1249
+ `Episode comment ${actionLabels[payload.action] ?? payload.action}`,
1250
+ payload.episodeId !== undefined ? ` Episode ID: ${payload.episodeId}` : null,
1251
+ payload.commentId !== undefined ? ` Comment ID: ${payload.commentId}` : null,
1252
+ payload.replyTo !== undefined ? ` Reply to: ${payload.replyTo}` : null,
1253
+ payload.value !== undefined ? ` Value: ${payload.value}` : null,
1254
+ ].filter(Boolean).join("\n");
1255
+ }
1256
+
1257
+ function formatBlogList(payload) {
1258
+ const lines = [
1259
+ `Blogs: ${payload.filters?.user ?? "-"}`,
1260
+ ` Range: ${formatPageRange(payload.offset ?? payload.filters?.offset, payload.data?.length, payload.total)}`,
1261
+ ];
1262
+ const blogs = Array.isArray(payload.data) ? payload.data : [];
1263
+
1264
+ if (blogs.length === 0) {
1265
+ lines.push("No results.");
1266
+ return lines.join("\n");
1267
+ }
1268
+
1269
+ const rows = blogs.map((entry) => ({
1270
+ id: entry.id ?? "-",
1271
+ title: entry.title ?? "-",
1272
+ replies: String(entry.replies ?? 0),
1273
+ visibility: entry.public ? "public" : "private",
1274
+ updated: entry.updatedAt ? formatTimestamp(entry.updatedAt).split(" ")[0] : "",
1275
+ }));
1276
+
1277
+ const table = formatTable(rows, [
1278
+ { key: "id", header: "#", minWidth: 5, align: "right" },
1279
+ { key: "title", header: "Title", minWidth: 8, maxWidth: 32, align: "left" },
1280
+ { key: "replies", header: "Replies", minWidth: 7, align: "right" },
1281
+ { key: "visibility", header: "Visibility", minWidth: 10, align: "left" },
1282
+ { key: "updated", header: "Updated", minWidth: 10, align: "left" },
1283
+ ]);
1284
+
1285
+ lines.push("");
1286
+ lines.push(table);
1287
+
1288
+ return lines.join("\n");
1289
+ }
1290
+
1291
+ function formatBlog(entry) {
1292
+ const lines = [
1293
+ `Blog #${entry.id ?? "-"}`,
1294
+ ` Title: ${entry.title ?? "-"}`,
1295
+ ` Author: ${formatUserLabel(entry.user, entry.uid)}`,
1296
+ ` Replies: ${entry.replies ?? 0}`,
1297
+ ` Views: ${entry.views ?? 0}`,
1298
+ ` Public: ${entry.public ? "Yes" : "No"}`,
1299
+ ` No reply: ${entry.noreply ? "Yes" : "No"}`,
1300
+ ` Related: ${entry.related ?? 0}`,
1301
+ ` Created at: ${formatTimestamp(entry.createdAt)}`,
1302
+ ` Updated at: ${formatTimestamp(entry.updatedAt)}`,
1303
+ ` URL: https://bgm.tv/blog/${entry.id ?? ""}`,
1304
+ ];
1305
+
1306
+ if (Array.isArray(entry.tags) && entry.tags.length > 0) {
1307
+ lines.push(` Tags: ${entry.tags.join(", ")}`);
1308
+ }
1309
+
1310
+ if (entry.content) {
1311
+ lines.push("");
1312
+ lines.push("Content");
1313
+ lines.push(indentBlock(truncateText(entry.content.trim(), 4000), 2));
1314
+ }
1315
+
1316
+ return lines.join("\n");
1317
+ }
1318
+
1319
+ function formatBlogComments(payload) {
1320
+ const lines = [
1321
+ `Blog comments: #${payload.entryId ?? "-"}`,
1322
+ ` Count: ${payload.data?.length ?? 0}`,
1323
+ ];
1324
+ const comments = Array.isArray(payload.data) ? payload.data : [];
1325
+
1326
+ if (comments.length === 0) {
1327
+ lines.push("No comments.");
1328
+ return lines.join("\n");
1329
+ }
1330
+
1331
+ for (const comment of comments) {
1332
+ lines.push("");
1333
+ lines.push(`• ${formatBlogCommentLine(comment)}`);
1334
+ if (comment.content) {
1335
+ lines.push(indentBlock(truncateText(comment.content.trim(), 800), 2));
1336
+ }
1337
+
1338
+ const replies = Array.isArray(comment.replies) ? comment.replies : [];
1339
+ for (const reply of replies) {
1340
+ lines.push(` - ${formatBlogCommentLine(reply)}`);
1341
+ if (reply.content) {
1342
+ lines.push(indentBlock(truncateText(reply.content.trim(), 500), 4));
1343
+ }
1344
+ }
1345
+ }
1346
+
1347
+ return lines.join("\n");
1348
+ }
1349
+
1350
+ function formatBlogPhotos(payload) {
1351
+ const lines = [
1352
+ `Blog photos: #${payload.entryId ?? "-"}`,
1353
+ ` Range: ${formatPageRange(payload.offset ?? payload.filters?.offset, payload.data?.length, payload.total)}`,
1354
+ ];
1355
+ const photos = Array.isArray(payload.data) ? payload.data : [];
1356
+
1357
+ if (photos.length === 0) {
1358
+ lines.push("No results.");
1359
+ return lines.join("\n");
1360
+ }
1361
+
1362
+ for (const photo of photos) {
1363
+ const pieces = [
1364
+ `#${photo.id ?? "-"}`,
1365
+ `${photo.vote ?? 0} votes`,
1366
+ ];
1367
+
1368
+ if (photo.createdAt) {
1369
+ pieces.push(`created ${formatTimestamp(photo.createdAt)}`);
1370
+ }
1371
+
1372
+ lines.push("");
1373
+ lines.push(`• ${pieces.join(" ")}`);
1374
+ lines.push(` ${photo.target ?? photo.icon ?? "-"}`);
1375
+ }
1376
+
1377
+ return lines.join("\n");
1378
+ }
1379
+
1380
+ function formatBlogSubjects(payload) {
1381
+ const lines = [
1382
+ `Blog subjects: #${payload.entryId ?? "-"}`,
1383
+ ` Count: ${payload.data?.length ?? 0}`,
1384
+ ];
1385
+ const subjects = Array.isArray(payload.data) ? payload.data : [];
1386
+
1387
+ if (subjects.length === 0) {
1388
+ lines.push("No results.");
1389
+ return lines.join("\n");
1390
+ }
1391
+
1392
+ for (const subject of subjects) {
1393
+ const pieces = [
1394
+ `#${subject.id ?? "-"}`,
1395
+ subject.nameCN || subject.name || "-",
1396
+ `[${formatSubjectType(subject.type)}]`,
1397
+ ];
1398
+
1399
+ if (subject.name && subject.nameCN && subject.name !== subject.nameCN) {
1400
+ pieces.push(`(${subject.name})`);
1401
+ }
1402
+ if (subject.date) {
1403
+ pieces.push(subject.date);
1404
+ }
1405
+
1406
+ lines.push("");
1407
+ lines.push(`• ${pieces.join(" ")}`);
1408
+ }
1409
+
1410
+ return lines.join("\n");
1411
+ }
1412
+
1413
+ function formatBlogCommentMutation(payload) {
1414
+ if (payload.action === "reply") {
1415
+ return [
1416
+ "Blog reply created",
1417
+ ` Blog ID: ${payload.entryId ?? "-"}`,
1418
+ ` Comment ID: ${payload.commentId ?? "-"}`,
1419
+ ` Reply to: ${payload.replyTo ?? 0}`,
1420
+ ` Blog URL: ${payload.url ?? "-"}`,
1421
+ ].join("\n");
1422
+ }
1423
+
1424
+ if (payload.action === "edit") {
1425
+ return [
1426
+ "Blog comment updated",
1427
+ ` Comment ID: ${payload.commentId ?? "-"}`,
1428
+ ].join("\n");
1429
+ }
1430
+
1431
+ if (payload.action === "delete") {
1432
+ return [
1433
+ "Blog comment deleted",
1434
+ ` Comment ID: ${payload.commentId ?? "-"}`,
1435
+ ].join("\n");
1436
+ }
1437
+
1438
+ return JSON.stringify(payload, null, 2);
1439
+ }
1440
+
1441
+ function formatIndex(index) {
1442
+ const lines = [
1443
+ `Index #${index.id ?? "-"}`,
1444
+ ` Title: ${index.title ?? "-"}`,
1445
+ ` Author: ${formatUserLabel(index.user, index.uid)}`,
1446
+ ` Type: ${formatIndexType(index.type)}`,
1447
+ ` Private: ${index.private ? "Yes" : "No"}`,
1448
+ ` Total related: ${index.total ?? 0}`,
1449
+ ` Replies: ${index.replies ?? 0}`,
1450
+ ` Collects: ${index.collects ?? 0}`,
1451
+ ` Created at: ${formatTimestamp(index.createdAt)}`,
1452
+ ` Updated at: ${formatTimestamp(index.updatedAt)}`,
1453
+ ` URL: https://bgm.tv/index/${index.id ?? ""}`,
1454
+ ];
1455
+
1456
+ if (index.stats && typeof index.stats === "object") {
1457
+ const stats = Object.entries(index.stats).filter(([, value]) => Number(value) > 0);
1458
+ if (stats.length > 0) {
1459
+ lines.push(` Stats: ${stats.map(([key, value]) => `${key} ${value}`).join(", ")}`);
1460
+ }
1461
+ }
1462
+
1463
+ if (index.desc) {
1464
+ lines.push("");
1465
+ lines.push("Description");
1466
+ lines.push(indentBlock(truncateText(index.desc.trim(), 4000), 2));
1467
+ }
1468
+
1469
+ return lines.join("\n");
1470
+ }
1471
+
1472
+ function formatIndexComments(payload) {
1473
+ const lines = [
1474
+ `Index comments: #${payload.indexId ?? "-"}`,
1475
+ ` Count: ${payload.data?.length ?? 0}`,
1476
+ ];
1477
+ const comments = Array.isArray(payload.data) ? payload.data : [];
1478
+
1479
+ if (comments.length === 0) {
1480
+ lines.push("No comments.");
1481
+ return lines.join("\n");
1482
+ }
1483
+
1484
+ for (const comment of comments) {
1485
+ lines.push("");
1486
+ lines.push(`• ${formatBlogCommentLine(comment)}`);
1487
+ if (comment.content) {
1488
+ lines.push(indentBlock(truncateText(comment.content.trim(), 800), 2));
1489
+ }
1490
+
1491
+ const replies = Array.isArray(comment.replies) ? comment.replies : [];
1492
+ for (const reply of replies) {
1493
+ lines.push(` - ${formatBlogCommentLine(reply)}`);
1494
+ if (reply.content) {
1495
+ lines.push(indentBlock(truncateText(reply.content.trim(), 500), 4));
1496
+ }
1497
+ }
1498
+ }
1499
+
1500
+ return lines.join("\n");
1501
+ }
1502
+
1503
+ function formatIndexRelated(payload) {
1504
+ const lines = [
1505
+ `Index related: #${payload.indexId ?? "-"}`,
1506
+ ` Range: ${formatPageRange(payload.offset ?? payload.filters?.offset, payload.data?.length, payload.total)}`,
1507
+ ];
1508
+ if (payload.filters?.cat !== undefined) {
1509
+ lines.push(` Category: ${formatIndexRelatedCategory(payload.filters.cat)}`);
1510
+ }
1511
+ if (payload.filters?.type !== undefined) {
1512
+ lines.push(` Type: ${formatSubjectType(payload.filters.type)}`);
1513
+ }
1514
+
1515
+ const items = Array.isArray(payload.data) ? payload.data : [];
1516
+ if (items.length === 0) {
1517
+ lines.push("No results.");
1518
+ return lines.join("\n");
1519
+ }
1520
+
1521
+ for (const item of items) {
1522
+ const pieces = [
1523
+ `#${item.id ?? "-"}`,
1524
+ `[${formatIndexRelatedCategory(item.cat)}]`,
1525
+ `target ${item.sid ?? "-"}`,
1526
+ describeIndexRelatedTarget(item),
1527
+ ].filter(Boolean);
1528
+
1529
+ if (item.order !== undefined) {
1530
+ pieces.push(`order ${item.order}`);
1531
+ }
1532
+ if (item.createdAt) {
1533
+ pieces.push(`created ${formatTimestamp(item.createdAt)}`);
1534
+ }
1535
+
1536
+ lines.push("");
1537
+ lines.push(`• ${pieces.join(" ")}`);
1538
+ if (item.comment) {
1539
+ lines.push(` Comment: ${item.comment}`);
1540
+ }
1541
+ if (item.award) {
1542
+ lines.push(` Award: ${item.award}`);
1543
+ }
1544
+ }
1545
+
1546
+ return lines.join("\n");
1547
+ }
1548
+
1549
+ function formatIndexMutation(payload) {
1550
+ if (payload.action === "create") {
1551
+ return [
1552
+ "Index created",
1553
+ ` Index ID: ${payload.indexId ?? "-"}`,
1554
+ ` Title: ${payload.title ?? "-"}`,
1555
+ ` Private: ${payload.private ? "Yes" : "No"}`,
1556
+ ` URL: https://bgm.tv/index/${payload.indexId ?? ""}`,
1557
+ ].join("\n");
1558
+ }
1559
+
1560
+ if (payload.action === "update") {
1561
+ return [
1562
+ "Index updated",
1563
+ ` Index ID: ${payload.indexId ?? "-"}`,
1564
+ ].join("\n");
1565
+ }
1566
+
1567
+ if (payload.action === "delete") {
1568
+ return [
1569
+ "Index deleted",
1570
+ ` Index ID: ${payload.indexId ?? "-"}`,
1571
+ ].join("\n");
1572
+ }
1573
+
1574
+ return JSON.stringify(payload, null, 2);
1575
+ }
1576
+
1577
+ function formatIndexCommentMutation(payload) {
1578
+ if (payload.action === "reply") {
1579
+ return [
1580
+ "Index comment created",
1581
+ ` Index ID: ${payload.indexId ?? "-"}`,
1582
+ ` Comment ID: ${payload.commentId ?? "-"}`,
1583
+ ` Reply to: ${payload.replyTo ?? 0}`,
1584
+ ` Index URL: ${payload.url ?? "-"}`,
1585
+ ].join("\n");
1586
+ }
1587
+
1588
+ if (payload.action === "edit") {
1589
+ return [
1590
+ "Index comment updated",
1591
+ ` Comment ID: ${payload.commentId ?? "-"}`,
1592
+ ].join("\n");
1593
+ }
1594
+
1595
+ if (payload.action === "delete") {
1596
+ return [
1597
+ "Index comment deleted",
1598
+ ` Comment ID: ${payload.commentId ?? "-"}`,
1599
+ ].join("\n");
1600
+ }
1601
+
1602
+ return JSON.stringify(payload, null, 2);
1603
+ }
1604
+
1605
+ function formatIndexRelatedMutation(payload) {
1606
+ if (payload.action === "add") {
1607
+ return [
1608
+ "Index related item added",
1609
+ ` Index ID: ${payload.indexId ?? "-"}`,
1610
+ ` Related ID: ${payload.relatedId ?? "-"}`,
1611
+ ` Category: ${formatIndexRelatedCategory(payload.cat)}`,
1612
+ ` Target ID: ${payload.sid ?? "-"}`,
1613
+ ` Order: ${payload.order ?? 0}`,
1614
+ ].join("\n");
1615
+ }
1616
+
1617
+ if (payload.action === "update") {
1618
+ return [
1619
+ "Index related item updated",
1620
+ ` Index ID: ${payload.indexId ?? "-"}`,
1621
+ ` Related ID: ${payload.relatedId ?? "-"}`,
1622
+ ` Order: ${payload.order ?? "-"}`,
1623
+ ].join("\n");
1624
+ }
1625
+
1626
+ if (payload.action === "delete") {
1627
+ return [
1628
+ "Index related item deleted",
1629
+ ` Index ID: ${payload.indexId ?? "-"}`,
1630
+ ` Related ID: ${payload.relatedId ?? "-"}`,
1631
+ ].join("\n");
1632
+ }
1633
+
1634
+ return JSON.stringify(payload, null, 2);
1635
+ }
1636
+
1637
+ function formatTimelineList(payload) {
1638
+ const title = payload.resource === "timeline-user-list"
1639
+ ? `Timeline: ${payload.filters?.user ?? "-"}`
1640
+ : "Timeline";
1641
+ const lines = [
1642
+ title,
1643
+ ` Returned: ${payload.data?.length ?? 0}`,
1644
+ ];
1645
+
1646
+ if (payload.resource === "timeline-list") {
1647
+ lines.push(` Mode: ${payload.filters?.mode ?? "all"}`);
1648
+ }
1649
+ if (payload.filters?.until !== undefined) {
1650
+ lines.push(` Until: #${payload.filters.until}`);
1651
+ }
1652
+
1653
+ const entries = Array.isArray(payload.data) ? payload.data : [];
1654
+ if (entries.length === 0) {
1655
+ lines.push("No results.");
1656
+ return lines.join("\n");
1657
+ }
1658
+
1659
+ for (const entry of entries) {
1660
+ lines.push("");
1661
+ lines.push(`• ${formatTimelineLine(entry)}`);
1662
+
1663
+ const memoSummary = formatTimelineMemoSummary(entry.memo);
1664
+ if (memoSummary) {
1665
+ lines.push(` ${truncateText(memoSummary, 240)}`);
1666
+ }
1667
+
1668
+ if (entry.source?.name || entry.source?.url) {
1669
+ lines.push(` Source: ${formatTimelineSource(entry.source)}`);
1670
+ }
1671
+ }
1672
+
1673
+ return lines.join("\n");
1674
+ }
1675
+
1676
+ function formatTimelineReplies(payload) {
1677
+ const lines = [
1678
+ `Timeline replies: #${payload.timelineId ?? "-"}`,
1679
+ ` Count: ${payload.data?.length ?? 0}`,
1680
+ ];
1681
+ const comments = Array.isArray(payload.data) ? payload.data : [];
1682
+
1683
+ if (comments.length === 0) {
1684
+ lines.push("No replies.");
1685
+ return lines.join("\n");
1686
+ }
1687
+
1688
+ for (const comment of comments) {
1689
+ lines.push("");
1690
+ lines.push(`• ${formatBlogCommentLine(comment)}`);
1691
+ if (comment.content) {
1692
+ lines.push(indentBlock(truncateText(comment.content.trim(), 800), 2));
1693
+ }
1694
+
1695
+ const replies = Array.isArray(comment.replies) ? comment.replies : [];
1696
+ for (const reply of replies) {
1697
+ lines.push(` - ${formatBlogCommentLine(reply)}`);
1698
+ if (reply.content) {
1699
+ lines.push(indentBlock(truncateText(reply.content.trim(), 500), 4));
1700
+ }
1701
+ }
1702
+ }
1703
+
1704
+ return lines.join("\n");
1705
+ }
1706
+
1707
+ function formatTimelineMutation(payload) {
1708
+ if (payload.action === "say") {
1709
+ return [
1710
+ "Timeline status created",
1711
+ ` Timeline ID: ${payload.timelineId ?? "-"}`,
1712
+ ].join("\n");
1713
+ }
1714
+
1715
+ if (payload.action === "reply") {
1716
+ return [
1717
+ "Timeline reply created",
1718
+ ` Timeline ID: ${payload.timelineId ?? "-"}`,
1719
+ ` Comment ID: ${payload.commentId ?? "-"}`,
1720
+ ` Reply to: ${payload.replyTo ?? 0}`,
1721
+ ].join("\n");
1722
+ }
1723
+
1724
+ if (payload.action === "delete") {
1725
+ return [
1726
+ "Timeline deleted",
1727
+ ` Timeline ID: ${payload.timelineId ?? "-"}`,
1728
+ ].join("\n");
1729
+ }
1730
+
1731
+ if (payload.action === "like") {
1732
+ return [
1733
+ "Timeline reaction saved",
1734
+ ` Timeline ID: ${payload.timelineId ?? "-"}`,
1735
+ ` Value: ${payload.value ?? "-"}`,
1736
+ ].join("\n");
1737
+ }
1738
+
1739
+ if (payload.action === "unlike") {
1740
+ return [
1741
+ "Timeline reaction removed",
1742
+ ` Timeline ID: ${payload.timelineId ?? "-"}`,
1743
+ ].join("\n");
1744
+ }
1745
+
1746
+ return JSON.stringify(payload, null, 2);
1747
+ }
1748
+
1749
+ function formatTimelineEvents(payload) {
1750
+ const events = Array.isArray(payload.data) ? payload.data : [];
1751
+ const lines = [
1752
+ "Timeline events",
1753
+ ` Returned: ${events.length}`,
1754
+ ` Mode: ${payload.filters?.mode ?? "all"}`,
1755
+ payload.filters?.cat !== undefined ? ` Cat: ${formatTimelineCat(payload.filters.cat)}` : null,
1756
+ ` Limit: ${payload.filters?.limit ?? "-"}`,
1757
+ ` Timeout: ${payload.filters?.timeoutSeconds ?? "-"}s`,
1758
+ ].filter(Boolean);
1759
+
1760
+ if (events.length === 0) {
1761
+ lines.push("No events received before the timeout.");
1762
+ return lines.join("\n");
1763
+ }
1764
+
1765
+ for (const event of events) {
1766
+ const eventName = event.event ?? "event";
1767
+ lines.push("");
1768
+ if (event.timeline) {
1769
+ lines.push(`• ${eventName}: ${formatTimelineLine(event.timeline)}`);
1770
+ const memoSummary = formatTimelineMemoSummary(event.timeline.memo);
1771
+ if (memoSummary) {
1772
+ lines.push(` ${truncateText(memoSummary, 240)}`);
1773
+ }
1774
+ } else if (event.data !== undefined) {
1775
+ lines.push(`• ${eventName}: ${truncateText(String(event.data), 240)}`);
1776
+ } else {
1777
+ lines.push(`• ${eventName}`);
1778
+ }
1779
+ }
1780
+
1781
+ return lines.join("\n");
1782
+ }
1783
+
1784
+ function describeIndexRelatedTarget(item) {
1785
+ if (item.subject) {
1786
+ return item.subject.nameCN || item.subject.name || null;
1787
+ }
1788
+ if (item.character) {
1789
+ return item.character.nameCN || item.character.name || null;
1790
+ }
1791
+ if (item.person) {
1792
+ return item.person.nameCN || item.person.name || null;
1793
+ }
1794
+ if (item.episode) {
1795
+ return item.episode.nameCN || item.episode.name || `Episode #${item.episode.id ?? item.sid}`;
1796
+ }
1797
+ if (item.blog) {
1798
+ return item.blog.title || null;
1799
+ }
1800
+ if (item.groupTopic) {
1801
+ return item.groupTopic.title || null;
1802
+ }
1803
+ if (item.subjectTopic) {
1804
+ return item.subjectTopic.title || null;
1805
+ }
1806
+ return null;
1807
+ }
1808
+
1809
+ function formatIndexType(value) {
1810
+ return {
1811
+ 0: "User",
1812
+ 1: "Public",
1813
+ 2: "Award",
1814
+ }[value] ?? String(value ?? "-");
1815
+ }
1816
+
1817
+ function formatIndexRelatedCategory(value) {
1818
+ return {
1819
+ 0: "Subject",
1820
+ 1: "Character",
1821
+ 2: "Person",
1822
+ 3: "Episode",
1823
+ 4: "Blog",
1824
+ 5: "Group Topic",
1825
+ 6: "Subject Topic",
1826
+ }[value] ?? String(value ?? "-");
1827
+ }
1828
+
1829
+ function formatGroupList(payload) {
1830
+ const lines = [
1831
+ payload.title ?? "Groups",
1832
+ ` Range: ${formatPageRange(payload.offset ?? payload.filters?.offset, payload.data?.length, payload.total)}`,
1833
+ ` Mode: ${payload.filters?.mode ?? "all"}`,
1834
+ ` Sort: ${payload.filters?.sort ?? "created"}`,
1835
+ ];
1836
+ if (payload.username) {
1837
+ lines.push(` User: ${payload.username}`);
1838
+ }
1839
+ const groups = Array.isArray(payload.data) ? payload.data : [];
1840
+
1841
+ if (groups.length === 0) {
1842
+ lines.push("No results.");
1843
+ return lines.join("\n");
1844
+ }
1845
+
1846
+ const rows = groups.map((group) => ({
1847
+ id: group.id ?? "-",
1848
+ title: group.title || "-",
1849
+ slug: group.name || "-",
1850
+ members: String(group.members ?? 0),
1851
+ topics: String(group.topics ?? 0),
1852
+ created: group.createdAt ? formatTimestamp(group.createdAt).split(" ")[0] : "",
1853
+ }));
1854
+
1855
+ const table = formatTable(rows, [
1856
+ { key: "id", header: "#", minWidth: 5, align: "right" },
1857
+ { key: "title", header: "Title", minWidth: 8, maxWidth: 24, align: "left" },
1858
+ { key: "slug", header: "Slug", minWidth: 8, maxWidth: 16, align: "left" },
1859
+ { key: "members", header: "Members", minWidth: 7, align: "right" },
1860
+ { key: "topics", header: "Topics", minWidth: 6, align: "right" },
1861
+ { key: "created", header: "Created", minWidth: 10, align: "left" },
1862
+ ]);
1863
+
1864
+ lines.push("");
1865
+ lines.push(table);
1866
+
1867
+ return lines.join("\n");
1868
+ }
1869
+
1870
+ function formatGroup(group) {
1871
+ const lines = [
1872
+ `Group #${group.id ?? "-"}`,
1873
+ ` Title: ${group.title ?? "-"}`,
1874
+ ` Slug: ${group.name ?? "-"}`,
1875
+ ` Members: ${group.members ?? 0}`,
1876
+ ` Topics: ${group.topics ?? 0}`,
1877
+ ` Posts: ${group.posts ?? 0}`,
1878
+ ` Accessible: ${group.accessible ? "Yes" : "No"}`,
1879
+ ` NSFW: ${group.nsfw ? "Yes" : "No"}`,
1880
+ ];
1881
+
1882
+ if (group.creator) {
1883
+ lines.push(` Creator: ${formatUserLabel(group.creator)}`);
1884
+ } else if (group.creatorID) {
1885
+ lines.push(` Creator ID: ${group.creatorID}`);
1886
+ }
1887
+ if (group.createdAt) {
1888
+ lines.push(` Created at: ${formatTimestamp(group.createdAt)}`);
1889
+ }
1890
+ if (group.membership?.role !== undefined) {
1891
+ lines.push(` My role: ${formatGroupMemberRole(group.membership.role)}`);
1892
+ }
1893
+ if (group.description) {
1894
+ lines.push("");
1895
+ lines.push("Description");
1896
+ lines.push(indentBlock(truncateText(group.description.trim(), 800), 2));
1897
+ }
1898
+ if (group.name) {
1899
+ lines.push(` URL: https://bgm.tv/group/${group.name}`);
1900
+ }
1901
+
1902
+ return lines.join("\n");
1903
+ }
1904
+
1905
+ function formatMonoDetail(payload) {
1906
+ const item = payload.data ?? {};
1907
+ const kind = payload.resource === "person" ? "Person" : "Character";
1908
+ const lines = [
1909
+ `${kind} #${item.id ?? "-"}`,
1910
+ ` Name: ${item.name ?? "-"}`,
1911
+ ];
1912
+
1913
+ if (item.nameCN) {
1914
+ lines.push(` Chinese name: ${item.nameCN}`);
1915
+ }
1916
+ if (payload.resource === "person" && Array.isArray(item.career) && item.career.length > 0) {
1917
+ lines.push(` Career: ${item.career.join(", ")}`);
1918
+ }
1919
+ if (payload.resource === "person" && item.type !== undefined) {
1920
+ lines.push(` Type: ${formatPersonType(item.type)}`);
1921
+ }
1922
+ if (payload.resource === "character" && item.role !== undefined) {
1923
+ lines.push(` Role: ${formatCharacterRole(item.role)}`);
1924
+ }
1925
+ lines.push(` Comments: ${item.comment ?? 0}`);
1926
+ lines.push(` Collects: ${item.collects ?? 0}`);
1927
+ if (item.nsfw) {
1928
+ lines.push(" NSFW: Yes");
1929
+ }
1930
+ if (item.info) {
1931
+ lines.push(` Info: ${truncateText(item.info, 180)}`);
1932
+ }
1933
+
1934
+ const infobox = formatInfoboxSummary(item.infobox);
1935
+ if (infobox.length > 0) {
1936
+ lines.push("");
1937
+ lines.push("Infobox");
1938
+ lines.push(...infobox.map((line) => ` ${line}`));
1939
+ }
1940
+
1941
+ if (item.summary) {
1942
+ lines.push("");
1943
+ lines.push("Summary");
1944
+ lines.push(indentBlock(truncateText(item.summary.trim(), 800), 2));
1945
+ }
1946
+ if (item.images?.large || item.images?.medium) {
1947
+ lines.push("");
1948
+ lines.push(`Image: ${item.images.large ?? item.images.medium}`);
1949
+ }
1950
+
1951
+ return lines.join("\n");
1952
+ }
1953
+
1954
+ function formatGenericP1List(payload) {
1955
+ const title = payload.title ?? String(payload.resource ?? "Results");
1956
+ const items = Array.isArray(payload.data) ? payload.data : [];
1957
+ const lines = [
1958
+ title,
1959
+ ` Range: ${formatPageRange(payload.filters?.offset ?? payload.offset, items.length, payload.total)}`,
1960
+ ];
1961
+
1962
+ if (payload.username) {
1963
+ lines.push(` User: ${payload.username}`);
1964
+ }
1965
+ if (payload.subjectId) {
1966
+ lines.push(` Subject ID: ${payload.subjectId}`);
1967
+ }
1968
+
1969
+ if (items.length === 0) {
1970
+ lines.push("No results.");
1971
+ return lines.join("\n");
1972
+ }
1973
+
1974
+ const { rows, columns } = buildGenericP1Table(payload.resource, items);
1975
+
1976
+ lines.push("");
1977
+ lines.push(formatTable(rows, columns));
1978
+ return lines.join("\n");
1979
+ }
1980
+
1981
+ function buildGenericP1Table(resource, items) {
1982
+ if (["user-friends", "user-followers"].includes(resource)) {
1983
+ return {
1984
+ rows: items.map((user) => ({
1985
+ id: user.id ?? "-",
1986
+ username: user.username ?? "-",
1987
+ nickname: user.nickname ?? "-",
1988
+ joined: user.joinedAt ? formatTimestamp(user.joinedAt).split(" ")[0] : "",
1989
+ sign: user.sign ?? "",
1990
+ })),
1991
+ columns: [
1992
+ { key: "id", header: "#", minWidth: 5, align: "right" },
1993
+ { key: "username", header: "Username", minWidth: 10, maxWidth: 18, align: "left" },
1994
+ { key: "nickname", header: "Nickname", minWidth: 10, maxWidth: 18, align: "left" },
1995
+ { key: "joined", header: "Joined", minWidth: 10, align: "left" },
1996
+ { key: "sign", header: "Sign", minWidth: 8, maxWidth: 30, align: "left" },
1997
+ ],
1998
+ };
1999
+ }
2000
+
2001
+ if (["character-search", "collection-characters"].includes(resource)) {
2002
+ return {
2003
+ rows: items.map((item) => ({
2004
+ id: item.id ?? "-",
2005
+ name: formatNamePair(item),
2006
+ role: formatCharacterRole(item.role),
2007
+ comments: String(item.comment ?? 0),
2008
+ info: item.info ?? "",
2009
+ })),
2010
+ columns: [
2011
+ { key: "id", header: "#", minWidth: 5, align: "right" },
2012
+ { key: "name", header: "Character", minWidth: 14, maxWidth: 32, align: "left" },
2013
+ { key: "role", header: "Role", minWidth: 8, maxWidth: 10, align: "left" },
2014
+ { key: "comments", header: "Comments", minWidth: 8, align: "right" },
2015
+ { key: "info", header: "Info", minWidth: 12, maxWidth: 34, align: "left" },
2016
+ ],
2017
+ };
2018
+ }
2019
+
2020
+ if (["person-search", "collection-persons"].includes(resource)) {
2021
+ return {
2022
+ rows: items.map((item) => ({
2023
+ id: item.id ?? "-",
2024
+ name: formatNamePair(item),
2025
+ career: Array.isArray(item.career) ? item.career.join(", ") : "",
2026
+ comments: String(item.comment ?? 0),
2027
+ info: item.info ?? "",
2028
+ })),
2029
+ columns: [
2030
+ { key: "id", header: "#", minWidth: 5, align: "right" },
2031
+ { key: "name", header: "Person", minWidth: 14, maxWidth: 32, align: "left" },
2032
+ { key: "career", header: "Career", minWidth: 8, maxWidth: 22, align: "left" },
2033
+ { key: "comments", header: "Comments", minWidth: 8, align: "right" },
2034
+ { key: "info", header: "Info", minWidth: 12, maxWidth: 34, align: "left" },
2035
+ ],
2036
+ };
2037
+ }
2038
+
2039
+ if (resource === "subject-comments") {
2040
+ return {
2041
+ rows: items.map((item) => ({
2042
+ id: item.id ?? "-",
2043
+ user: formatUserLabel(item.user),
2044
+ status: formatCollectionStatus(item.type),
2045
+ rate: item.rate ? String(item.rate) : "",
2046
+ comment: item.comment ?? "",
2047
+ updated: item.updatedAt ? formatTimestamp(item.updatedAt).split(" ")[0] : "",
2048
+ })),
2049
+ columns: [
2050
+ { key: "id", header: "#", minWidth: 7, align: "right" },
2051
+ { key: "user", header: "User", minWidth: 10, maxWidth: 18, align: "left" },
2052
+ { key: "status", header: "Status", minWidth: 8, maxWidth: 10, align: "left" },
2053
+ { key: "rate", header: "Rate", minWidth: 4, align: "right" },
2054
+ { key: "comment", header: "Comment", minWidth: 16, maxWidth: 42, align: "left" },
2055
+ { key: "updated", header: "Updated", minWidth: 10, align: "left" },
2056
+ ],
2057
+ };
2058
+ }
2059
+
2060
+ if (resource === "subject-reviews") {
2061
+ return {
2062
+ rows: items.map((item) => ({
2063
+ id: item.entry?.id ?? item.id ?? "-",
2064
+ title: item.entry?.title ?? "-",
2065
+ user: formatUserLabel(item.user),
2066
+ replies: String(item.entry?.replies ?? ""),
2067
+ updated: item.entry?.updatedAt ? formatTimestamp(item.entry.updatedAt).split(" ")[0] : "",
2068
+ })),
2069
+ columns: [
2070
+ { key: "id", header: "#", minWidth: 7, align: "right" },
2071
+ { key: "title", header: "Review", minWidth: 16, maxWidth: 44, align: "left" },
2072
+ { key: "user", header: "User", minWidth: 10, maxWidth: 18, align: "left" },
2073
+ { key: "replies", header: "Replies", minWidth: 7, align: "right" },
2074
+ { key: "updated", header: "Updated", minWidth: 10, align: "left" },
2075
+ ],
2076
+ };
2077
+ }
2078
+
2079
+ if (["subject-topics", "subject-recent-topics", "trending-subject-topics"].includes(resource)) {
2080
+ return {
2081
+ rows: items.map((item) => ({
2082
+ id: item.id ?? "-",
2083
+ title: item.title ?? "-",
2084
+ subject: formatNamePair(item.subject),
2085
+ user: formatUserLabel(item.creator),
2086
+ replies: String(item.replyCount ?? item.replies?.length ?? 0),
2087
+ updated: item.updatedAt ? formatTimestamp(item.updatedAt).split(" ")[0] : "",
2088
+ })),
2089
+ columns: [
2090
+ { key: "id", header: "#", minWidth: 7, align: "right" },
2091
+ { key: "title", header: "Topic", minWidth: 16, maxWidth: 36, align: "left" },
2092
+ { key: "subject", header: "Subject", minWidth: 12, maxWidth: 28, align: "left" },
2093
+ { key: "user", header: "User", minWidth: 10, maxWidth: 16, align: "left" },
2094
+ { key: "replies", header: "Replies", minWidth: 7, align: "right" },
2095
+ { key: "updated", header: "Updated", minWidth: 10, align: "left" },
2096
+ ],
2097
+ };
2098
+ }
2099
+
2100
+ if (["subject-characters", "person-casts"].includes(resource)) {
2101
+ return {
2102
+ rows: items.map((item) => ({
2103
+ id: item.character?.id ?? "-",
2104
+ character: formatNamePair(item.character),
2105
+ role: formatCharacterRole(item.character?.role ?? item.type),
2106
+ subject: formatSubjectRefs(item.relations),
2107
+ count: String(item.character?.comment ?? ""),
2108
+ })),
2109
+ columns: [
2110
+ { key: "id", header: "#", minWidth: 5, align: "right" },
2111
+ { key: "character", header: "Character", minWidth: 14, maxWidth: 32, align: "left" },
2112
+ { key: "role", header: "Role", minWidth: 8, maxWidth: 10, align: "left" },
2113
+ { key: "subject", header: "Subject", minWidth: 12, maxWidth: 30, align: "left" },
2114
+ { key: "count", header: "Comments", minWidth: 8, align: "right" },
2115
+ ],
2116
+ };
2117
+ }
2118
+
2119
+ if (["character-casts", "person-works", "subject-relations", "subject-recs", "trending-subjects"].includes(resource)) {
2120
+ return {
2121
+ rows: items.map((item) => ({
2122
+ id: item.subject?.id ?? "-",
2123
+ subject: formatNamePair(item.subject),
2124
+ type: formatSubjectType(item.subject?.type),
2125
+ meta: describeSubjectListMeta(resource, item),
2126
+ score: item.subject?.rating?.score !== undefined ? String(item.subject.rating.score) : "",
2127
+ })),
2128
+ columns: [
2129
+ { key: "id", header: "#", minWidth: 5, align: "right" },
2130
+ { key: "subject", header: "Subject", minWidth: 14, maxWidth: 34, align: "left" },
2131
+ { key: "type", header: "Type", minWidth: 6, maxWidth: 8, align: "left" },
2132
+ { key: "meta", header: "Meta", minWidth: 10, maxWidth: 30, align: "left" },
2133
+ { key: "score", header: "Score", minWidth: 5, align: "right" },
2134
+ ],
2135
+ };
2136
+ }
2137
+
2138
+ if (["subject-staff"].includes(resource)) {
2139
+ return {
2140
+ rows: items.map((item) => ({
2141
+ id: item.staff?.id ?? "-",
2142
+ person: formatNamePair(item.staff),
2143
+ career: Array.isArray(item.staff?.career) ? item.staff.career.join(", ") : "",
2144
+ positions: formatPositions(item.positions),
2145
+ })),
2146
+ columns: [
2147
+ { key: "id", header: "#", minWidth: 5, align: "right" },
2148
+ { key: "person", header: "Person", minWidth: 14, maxWidth: 30, align: "left" },
2149
+ { key: "career", header: "Career", minWidth: 8, maxWidth: 22, align: "left" },
2150
+ { key: "positions", header: "Positions", minWidth: 12, maxWidth: 34, align: "left" },
2151
+ ],
2152
+ };
2153
+ }
2154
+
2155
+ if (["index-list", "collection-indexes", "subject-indexes"].includes(resource)) {
2156
+ return {
2157
+ rows: items.map((item) => ({
2158
+ id: item.id ?? "-",
2159
+ title: item.title ?? "-",
2160
+ total: String(item.total ?? describeListCount(item, item)),
2161
+ visibility: item.private ? "Private" : "Public",
2162
+ updated: item.updatedAt ? formatTimestamp(item.updatedAt).split(" ")[0] : "",
2163
+ })),
2164
+ columns: [
2165
+ { key: "id", header: "#", minWidth: 6, align: "right" },
2166
+ { key: "title", header: "Index", minWidth: 16, maxWidth: 42, align: "left" },
2167
+ { key: "total", header: "Items", minWidth: 6, align: "right" },
2168
+ { key: "visibility", header: "Visibility", minWidth: 10, align: "left" },
2169
+ { key: "updated", header: "Updated", minWidth: 10, align: "left" },
2170
+ ],
2171
+ };
2172
+ }
2173
+
2174
+ const rows = items.map((item) => {
2175
+ const target = pickListTarget(item);
2176
+ return {
2177
+ id: target.id ?? item.id ?? item.sid ?? "-",
2178
+ title: describeListTitle(target, item),
2179
+ user: describeListUser(item),
2180
+ count: describeListCount(target, item),
2181
+ };
2182
+ });
2183
+ return {
2184
+ rows,
2185
+ columns: [
2186
+ { key: "id", header: "#", minWidth: 5, align: "right" },
2187
+ { key: "title", header: "Title", minWidth: 12, maxWidth: 44, align: "left" },
2188
+ { key: "user", header: "User", minWidth: 8, maxWidth: 18, align: "left" },
2189
+ { key: "count", header: "Count", minWidth: 6, align: "right" },
2190
+ ],
2191
+ };
2192
+ }
2193
+
2194
+ function formatNamePair(item) {
2195
+ if (!isObject(item)) {
2196
+ return "-";
2197
+ }
2198
+
2199
+ const primary = item.nameCN || item.nameCn || item.title || item.name || item.nickname || item.username;
2200
+ const secondary = item.name && primary !== item.name ? item.name : "";
2201
+ return secondary ? `${primary} / ${secondary}` : (primary || "-");
2202
+ }
2203
+
2204
+ function formatInfoboxSummary(infobox) {
2205
+ if (!Array.isArray(infobox)) {
2206
+ return [];
2207
+ }
2208
+
2209
+ return infobox.slice(0, 8).map((entry) => {
2210
+ const key = entry?.key ?? "-";
2211
+ const values = Array.isArray(entry?.values)
2212
+ ? entry.values.map((item) => item?.v ?? item).filter(Boolean).join(", ")
2213
+ : entry?.value ?? entry?.values ?? "";
2214
+ return `${key}: ${truncateText(values, 120)}`;
2215
+ }).filter((line) => !line.endsWith(": "));
2216
+ }
2217
+
2218
+ function formatPersonType(type) {
2219
+ return {
2220
+ 1: "Individual",
2221
+ 2: "Company",
2222
+ 3: "Group",
2223
+ }[type] ?? String(type ?? "-");
2224
+ }
2225
+
2226
+ function formatCharacterRole(role) {
2227
+ return {
2228
+ 1: "Main",
2229
+ 2: "Supporting",
2230
+ 3: "Guest",
2231
+ }[role] ?? String(role ?? "-");
2232
+ }
2233
+
2234
+ function formatSubjectRefs(relations) {
2235
+ if (!Array.isArray(relations) || relations.length === 0) {
2236
+ return "";
2237
+ }
2238
+
2239
+ return relations
2240
+ .slice(0, 2)
2241
+ .map((relation) => formatNamePair(relation.subject))
2242
+ .filter(Boolean)
2243
+ .join(", ");
2244
+ }
2245
+
2246
+ function describeSubjectListMeta(resource, item) {
2247
+ if (resource === "trending-subjects") {
2248
+ return item.count !== undefined ? `${item.count} watchers` : "";
2249
+ }
2250
+ if (resource === "subject-relations") {
2251
+ return item.relation?.cn || item.relation?.en || item.relation?.jp || "";
2252
+ }
2253
+ if (resource === "character-casts") {
2254
+ return formatCastPeople(item.casts);
2255
+ }
2256
+ if (resource === "person-works") {
2257
+ return formatPositions(item.positions);
2258
+ }
2259
+ return describeListCount(item.subject, item);
2260
+ }
2261
+
2262
+ function formatCastPeople(casts) {
2263
+ if (!Array.isArray(casts) || casts.length === 0) {
2264
+ return "";
2265
+ }
2266
+
2267
+ return casts
2268
+ .slice(0, 3)
2269
+ .map((cast) => {
2270
+ const person = formatNamePair(cast.person);
2271
+ return cast.summary ? `${person} (${cast.summary})` : person;
2272
+ })
2273
+ .join(", ");
2274
+ }
2275
+
2276
+ function formatPositions(positions) {
2277
+ if (!Array.isArray(positions) || positions.length === 0) {
2278
+ return "";
2279
+ }
2280
+
2281
+ return positions
2282
+ .slice(0, 4)
2283
+ .map((position) => {
2284
+ const label = position.type?.cn || position.type?.en || position.type?.jp || position.summary || position.type?.id;
2285
+ return position.summary && label !== position.summary
2286
+ ? `${label}: ${position.summary}`
2287
+ : String(label ?? "");
2288
+ })
2289
+ .filter(Boolean)
2290
+ .join(", ");
2291
+ }
2292
+
2293
+ function pickListTarget(item) {
2294
+ return item?.subject
2295
+ ?? item?.character
2296
+ ?? item?.person
2297
+ ?? item?.user
2298
+ ?? item?.group
2299
+ ?? item?.index
2300
+ ?? item?.topic
2301
+ ?? item;
2302
+ }
2303
+
2304
+ function describeListTitle(target, item) {
2305
+ return target?.nameCN
2306
+ || target?.nameCn
2307
+ || target?.title
2308
+ || target?.name
2309
+ || target?.nickname
2310
+ || target?.username
2311
+ || item?.content
2312
+ || item?.summary
2313
+ || "-";
2314
+ }
2315
+
2316
+ function describeListUser(item) {
2317
+ const user = item?.user ?? item?.creator;
2318
+ return user?.nickname || user?.username || "";
2319
+ }
2320
+
2321
+ function describeListCount(target, item) {
2322
+ const value = item?.replies
2323
+ ?? item?.replyCount
2324
+ ?? target?.replies
2325
+ ?? target?.comments
2326
+ ?? target?.collects
2327
+ ?? target?.followers
2328
+ ?? target?.watchers
2329
+ ?? item?.count
2330
+ ?? "";
2331
+ return value === "" ? "" : String(value);
2332
+ }
2333
+
2334
+ function formatGroupHot(payload) {
2335
+ const lines = [
2336
+ `Hot groups (${payload.filters?.window ?? "day"})`,
2337
+ ` Topics sampled: ${payload.filters?.sampledTopics ?? payload.data?.length ?? 0}`,
2338
+ ` Mode: ${payload.filters?.mode ?? "all"}`,
2339
+ ` Scan cap: ${payload.filters?.scan ?? "-"}`,
2340
+ ];
2341
+ const groups = Array.isArray(payload.data) ? payload.data : [];
2342
+
2343
+ if (groups.length === 0) {
2344
+ lines.push("No results.");
2345
+ return lines.join("\n");
2346
+ }
2347
+
2348
+ for (const [index, group] of groups.entries()) {
2349
+ const pieces = [
2350
+ `#${index + 1}`,
2351
+ `${group.title ?? "-"}${group.name ? ` (${group.name})` : ""}`,
2352
+ `hot ${formatHotScore(group.hotScore)}`,
2353
+ `${group.topicCount ?? 0} active topics`,
2354
+ `${group.replyCount ?? 0} replies`,
2355
+ ];
2356
+ if (group.members) {
2357
+ pieces.push(`${group.members} members`);
2358
+ }
2359
+ if (group.latestActivityAt) {
2360
+ pieces.push(`last ${formatTimestamp(group.latestActivityAt)}`);
2361
+ }
2362
+
2363
+ lines.push("");
2364
+ lines.push(`• ${pieces.join(" ")}`);
2365
+
2366
+ if (Array.isArray(group.topTopics) && group.topTopics.length > 0) {
2367
+ lines.push(` Top topics: ${group.topTopics.map((topic) => `#${topic.id} ${topic.title}`).join(" | ")}`);
2368
+ }
2369
+ }
2370
+
2371
+ return lines.join("\n");
2372
+ }
2373
+
2374
+ function formatGroupLatestReplies(payload) {
2375
+ const lines = [
2376
+ "Latest replied group topics",
2377
+ ` Returned: ${payload.data?.length ?? 0}`,
2378
+ ` Mode: ${payload.filters?.mode ?? "all"}`,
2379
+ ` Scan cap: ${payload.filters?.scan ?? "-"}`,
2380
+ ];
2381
+ const topics = Array.isArray(payload.data) ? payload.data : [];
2382
+
2383
+ if (topics.length === 0) {
2384
+ lines.push("No results.");
2385
+ return lines.join("\n");
2386
+ }
2387
+
2388
+ for (const topic of topics) {
2389
+ lines.push("");
2390
+ lines.push(`• ${formatTopicLine(topic)}`);
2391
+ }
2392
+
2393
+ return lines.join("\n");
2394
+ }
2395
+
2396
+ function formatGroupMembers(payload) {
2397
+ const lines = [
2398
+ `Group members: ${payload.groupName ?? "-"}`,
2399
+ ` Range: ${formatPageRange(payload.offset ?? payload.filters?.offset, payload.data?.length, payload.total)}`,
2400
+ ` Role filter: ${formatGroupMemberRole(payload.filters?.role)}`,
2401
+ ];
2402
+ const members = Array.isArray(payload.data) ? payload.data : [];
2403
+
2404
+ if (members.length === 0) {
2405
+ lines.push("No results.");
2406
+ return lines.join("\n");
2407
+ }
2408
+
2409
+ const rows = members.map((member) => {
2410
+ const user = member.user ?? {};
2411
+ return {
2412
+ user: formatUserLabel(user, member.uid),
2413
+ role: formatGroupMemberRole(member.role),
2414
+ joined: member.joinedAt ? formatTimestamp(member.joinedAt).split(" ")[0] : "",
2415
+ };
2416
+ });
2417
+
2418
+ const table = formatTable(rows, [
2419
+ { key: "user", header: "User", minWidth: 8, maxWidth: 24, align: "left" },
2420
+ { key: "role", header: "Role", minWidth: 6, align: "left" },
2421
+ { key: "joined", header: "Joined", minWidth: 10, align: "left" },
2422
+ ]);
2423
+
2424
+ lines.push("");
2425
+ lines.push(table);
2426
+
2427
+ return lines.join("\n");
2428
+ }
2429
+
2430
+ function formatGroupTopics(payload) {
2431
+ const lines = [
2432
+ payload.resource === "group-recent-topics" ? "Recent group topics" : `Group topics: ${payload.groupName ?? "-"}`,
2433
+ ` Range: ${formatPageRange(payload.offset ?? payload.filters?.offset, payload.data?.length, payload.total)}`,
2434
+ ];
2435
+
2436
+ if (payload.resource === "group-recent-topics") {
2437
+ lines.push(` Mode: ${payload.filters?.mode ?? "all"}`);
2438
+ }
2439
+
2440
+ const topics = Array.isArray(payload.data) ? payload.data : [];
2441
+ if (topics.length === 0) {
2442
+ lines.push("No results.");
2443
+ return lines.join("\n");
2444
+ }
2445
+
2446
+ const rows = topics.map((topic) => ({
2447
+ id: topic.id ?? "-",
2448
+ title: topic.title ?? "-",
2449
+ replies: topic.replyCount !== undefined ? String(topic.replyCount) : "",
2450
+ author: topic.creator || topic.creatorID ? formatUserLabel(topic.creator, topic.creatorID) : "",
2451
+ updated: topic.updatedAt ? formatTimestamp(topic.updatedAt).split(" ")[0] : "",
2452
+ }));
2453
+
2454
+ const table = formatTable(rows, [
2455
+ { key: "id", header: "#", minWidth: 5, align: "right" },
2456
+ { key: "title", header: "Title", minWidth: 8, maxWidth: 32, align: "left" },
2457
+ { key: "replies", header: "Replies", minWidth: 7, align: "right" },
2458
+ { key: "author", header: "Author", minWidth: 8, maxWidth: 16, align: "left" },
2459
+ { key: "updated", header: "Updated", minWidth: 10, align: "left" },
2460
+ ]);
2461
+
2462
+ lines.push("");
2463
+ lines.push(table);
2464
+
2465
+ return lines.join("\n");
2466
+ }
2467
+
2468
+ function formatGroupHotTopics(payload) {
2469
+ const lines = [
2470
+ `Hot group topics (${payload.filters?.window ?? "day"})`,
2471
+ ` Topics sampled: ${payload.filters?.sampledTopics ?? payload.data?.length ?? 0}`,
2472
+ ` Mode: ${payload.filters?.mode ?? "all"}`,
2473
+ ` Scan cap: ${payload.filters?.scan ?? "-"}`,
2474
+ ];
2475
+ const topics = Array.isArray(payload.data) ? payload.data : [];
2476
+
2477
+ if (topics.length === 0) {
2478
+ lines.push("No results.");
2479
+ return lines.join("\n");
2480
+ }
2481
+
2482
+ for (const [index, topic] of topics.entries()) {
2483
+ const pieces = [
2484
+ `#${index + 1}`,
2485
+ `topic ${topic.id ?? "-"}`,
2486
+ topic.title ?? "-",
2487
+ `hot ${formatHotScore(topic.hotScore)}`,
2488
+ `${topic.replyCount ?? 0} replies`,
2489
+ ];
2490
+
2491
+ if (topic.group?.title) {
2492
+ pieces.push(`[${topic.group.title}]`);
2493
+ }
2494
+ if (topic.creator || topic.creatorID) {
2495
+ pieces.push(`by ${formatUserLabel(topic.creator, topic.creatorID)}`);
2496
+ }
2497
+ if (topic.updatedAt) {
2498
+ pieces.push(`updated ${formatTimestamp(topic.updatedAt)}`);
2499
+ }
2500
+
2501
+ lines.push("");
2502
+ lines.push(`• ${pieces.join(" ")}`);
2503
+ }
2504
+
2505
+ return lines.join("\n");
2506
+ }
2507
+
2508
+ function formatGroupTopic(topic) {
2509
+ const lines = [
2510
+ `Group topic #${topic.id ?? "-"}`,
2511
+ ` Title: ${topic.title ?? "-"}`,
2512
+ ` Group: ${topic.group?.title || "-"}${topic.group?.name ? ` (${topic.group.name})` : ""}`,
2513
+ ` Author: ${formatUserLabel(topic.creator, topic.creatorID)}`,
2514
+ ` Replies: ${topic.replyCount ?? topic.replies?.length ?? 0}`,
2515
+ ` Created at: ${formatTimestamp(topic.createdAt)}`,
2516
+ ` Updated at: ${formatTimestamp(topic.updatedAt)}`,
2517
+ ` URL: https://bgm.tv/group/topic/${topic.id ?? ""}`,
2518
+ ];
2519
+
2520
+ if (topic.content) {
2521
+ lines.push("");
2522
+ lines.push("Content");
2523
+ lines.push(indentBlock(truncateText(topic.content.trim(), 4000), 2));
2524
+ }
2525
+
2526
+ const replies = Array.isArray(topic.replies) ? topic.replies : [];
2527
+ const replyLimit = Number(topic.filters?.replyLimit ?? 20);
2528
+ if (replies.length > 0) {
2529
+ lines.push("");
2530
+ lines.push("Replies");
2531
+ for (const reply of replies.slice(0, replyLimit)) {
2532
+ lines.push(` • ${formatReplyLine(reply)}`);
2533
+ if (reply.content) {
2534
+ lines.push(indentBlock(truncateText(reply.content.trim(), 600), 4));
2535
+ }
2536
+ }
2537
+ if (replies.length > replyLimit) {
2538
+ lines.push(` ... ${replies.length - replyLimit} more replies`);
2539
+ }
2540
+ }
2541
+
2542
+ return lines.join("\n");
2543
+ }
2544
+
2545
+ function formatSubjectTopic(topic) {
2546
+ const replies = Array.isArray(topic.replies) ? topic.replies : [];
2547
+ const firstPost = topic.content ? null : replies[0];
2548
+ const displayReplies = topic.content ? replies : replies.slice(1);
2549
+ const content = topic.content ?? firstPost?.content;
2550
+ const lines = [
2551
+ `Subject topic #${topic.id ?? "-"}`,
2552
+ ` Title: ${topic.title ?? "-"}`,
2553
+ ` Subject: ${formatNamePair(topic.subject)}${topic.subject?.id ? ` (#${topic.subject.id})` : ""}`,
2554
+ ` Author: ${formatUserLabel(topic.creator, topic.creatorID)}`,
2555
+ ` Replies: ${topic.replyCount ?? displayReplies.length}`,
2556
+ ` Created at: ${formatTimestamp(topic.createdAt)}`,
2557
+ ` Updated at: ${formatTimestamp(topic.updatedAt)}`,
2558
+ ` URL: https://bgm.tv/subject/topic/${topic.id ?? ""}`,
2559
+ ];
2560
+
2561
+ if (content) {
2562
+ lines.push("");
2563
+ lines.push("Content");
2564
+ lines.push(indentBlock(truncateText(String(content).trim(), 4000), 2));
2565
+ }
2566
+
2567
+ if (displayReplies.length > 0) {
2568
+ lines.push("");
2569
+ lines.push("Replies");
2570
+ for (const reply of displayReplies) {
2571
+ lines.push(` • ${formatReplyLine(reply)}`);
2572
+ if (reply.content) {
2573
+ lines.push(indentBlock(truncateText(String(reply.content).trim(), 600), 4));
2574
+ }
2575
+ }
2576
+ }
2577
+
2578
+ return lines.join("\n");
2579
+ }
2580
+
2581
+ function formatGroupTopicMutation(payload) {
2582
+ if (payload.action === "create-topic") {
2583
+ return [
2584
+ "Group topic created",
2585
+ ` Group: ${payload.groupName ?? "-"}`,
2586
+ ` Topic ID: ${payload.topicId ?? "-"}`,
2587
+ ` Title: ${payload.title ?? "-"}`,
2588
+ ` URL: ${payload.url ?? "-"}`,
2589
+ ].join("\n");
2590
+ }
2591
+
2592
+ if (payload.action === "reply") {
2593
+ return [
2594
+ "Group reply created",
2595
+ ` Topic ID: ${payload.topicId ?? "-"}`,
2596
+ ` Post ID: ${payload.postId ?? "-"}`,
2597
+ ` Reply to: ${payload.replyTo ?? 0}`,
2598
+ ` Topic URL: ${payload.url ?? "-"}`,
2599
+ ].join("\n");
2600
+ }
2601
+
2602
+ if (payload.action === "edit-topic") {
2603
+ return [
2604
+ "Group topic updated",
2605
+ ` Topic ID: ${payload.topicId ?? "-"}`,
2606
+ ` Title: ${payload.title ?? "-"}`,
2607
+ ` URL: ${payload.url ?? "-"}`,
2608
+ ].join("\n");
2609
+ }
2610
+
2611
+ return JSON.stringify(payload, null, 2);
2612
+ }
2613
+
2614
+ function formatTopicMutation(payload) {
2615
+ const label = payload.scope === "subject" ? "Subject topic" : "Topic";
2616
+ const actionLabels = {
2617
+ "create-topic": "created",
2618
+ "edit-topic": "updated",
2619
+ reply: "reply created",
2620
+ };
2621
+
2622
+ const lines = [
2623
+ `${label} ${actionLabels[payload.action] ?? payload.action}`,
2624
+ payload.subjectId !== undefined ? ` Subject ID: ${payload.subjectId}` : null,
2625
+ payload.topicId !== undefined ? ` Topic ID: ${payload.topicId}` : null,
2626
+ payload.postId !== undefined ? ` Post ID: ${payload.postId}` : null,
2627
+ payload.replyTo !== undefined ? ` Reply to: ${payload.replyTo}` : null,
2628
+ payload.title ? ` Title: ${payload.title}` : null,
2629
+ payload.url ? ` URL: ${payload.url}` : null,
2630
+ ].filter(Boolean);
2631
+
2632
+ return lines.join("\n");
2633
+ }
2634
+
2635
+ function formatTopicPost(payload) {
2636
+ const post = payload.data ?? {};
2637
+ const lines = [
2638
+ `${capitalize(payload.scope ?? "topic")} post #${post.id ?? payload.postId ?? "-"}`,
2639
+ ` Author: ${formatUserLabel(post.creator, post.creatorID)}`,
2640
+ post.topic?.id ? ` Topic ID: ${post.topic.id}` : null,
2641
+ post.createdAt ? ` Created at: ${formatTimestamp(post.createdAt)}` : null,
2642
+ ].filter(Boolean);
2643
+
2644
+ if (post.content) {
2645
+ lines.push("");
2646
+ lines.push("Content");
2647
+ lines.push(indentBlock(truncateText(String(post.content).trim(), 4000), 2));
2648
+ }
2649
+
2650
+ return lines.join("\n");
2651
+ }
2652
+
2653
+ function formatPostMutation(payload) {
2654
+ const actionLabels = {
2655
+ "edit-post": "updated",
2656
+ "delete-post": "deleted",
2657
+ "like-post": "liked",
2658
+ "unlike-post": "unliked",
2659
+ };
2660
+
2661
+ return [
2662
+ `${capitalize(payload.scope ?? "topic")} post ${actionLabels[payload.action] ?? payload.action}`,
2663
+ ` Post ID: ${payload.postId ?? "-"}`,
2664
+ payload.value !== undefined ? ` Value: ${payload.value}` : null,
2665
+ ].filter(Boolean).join("\n");
2666
+ }
2667
+
2668
+ function formatSubjectCollectMutation(payload) {
2669
+ const actionLabels = {
2670
+ "like-collect": "liked",
2671
+ "unlike-collect": "unliked",
2672
+ };
2673
+
2674
+ return [
2675
+ `Subject collect ${actionLabels[payload.action] ?? payload.action}`,
2676
+ ` Collect ID: ${payload.collectId ?? "-"}`,
2677
+ payload.value !== undefined ? ` Value: ${payload.value}` : null,
2678
+ ].filter(Boolean).join("\n");
2679
+ }
2680
+
2681
+ function formatMonoCommentMutation(payload) {
2682
+ const actionLabels = {
2683
+ create: "created",
2684
+ edit: "updated",
2685
+ delete: "deleted",
2686
+ };
2687
+
2688
+ return [
2689
+ `${capitalize(payload.scope ?? "mono")} comment ${actionLabels[payload.action] ?? payload.action}`,
2690
+ payload.targetId !== undefined ? ` Target ID: ${payload.targetId}` : null,
2691
+ payload.commentId !== undefined ? ` Comment ID: ${payload.commentId}` : null,
2692
+ payload.replyTo !== undefined ? ` Reply to: ${payload.replyTo}` : null,
2693
+ ].filter(Boolean).join("\n");
2694
+ }
2695
+
2696
+ function formatMonoPhoto(payload) {
2697
+ const photo = payload.data ?? {};
2698
+ const lines = [
2699
+ `${capitalize(payload.scope ?? "mono")} photo #${photo.id ?? payload.photoId ?? "-"}`,
2700
+ payload.targetId !== undefined ? ` Target ID: ${payload.targetId}` : null,
2701
+ photo.creatorID !== undefined ? ` Creator ID: ${photo.creatorID}` : null,
2702
+ photo.vote !== undefined ? ` Votes: ${photo.vote}` : null,
2703
+ photo.createdAt ? ` Created at: ${formatTimestamp(photo.createdAt)}` : null,
2704
+ ].filter(Boolean);
2705
+
2706
+ const url = photo.target ?? photo.icon ?? photo.image ?? photo.url;
2707
+ if (url) {
2708
+ lines.push(` Image: ${url}`);
2709
+ }
2710
+ if (photo.comment) {
2711
+ lines.push("");
2712
+ lines.push(indentBlock(truncateText(String(photo.comment).trim(), 800), 2));
2713
+ }
2714
+
2715
+ return lines.join("\n");
2716
+ }
2717
+
2718
+ function formatMonoPhotoComments(payload) {
2719
+ const lines = [
2720
+ `${capitalize(payload.scope ?? "mono")} photo comments: #${payload.photoId ?? "-"}`,
2721
+ payload.targetId !== undefined ? ` Target ID: ${payload.targetId}` : null,
2722
+ ` Count: ${payload.data?.length ?? 0}`,
2723
+ ].filter(Boolean);
2724
+ appendCommentTree(lines, payload.data, "No comments.");
2725
+ return lines.join("\n");
2726
+ }
2727
+
2728
+ function formatSimpleCollectionMutation(payload) {
2729
+ const actionLabel = payload.action === "delete" ? "removed" : "added";
2730
+ return [
2731
+ `${capitalize(payload.kind ?? "item")} collection ${actionLabel}`,
2732
+ ` ID: ${payload.id ?? "-"}`,
2733
+ ].join("\n");
2734
+ }
2735
+
2736
+ function capitalize(value) {
2737
+ const text = String(value ?? "");
2738
+ return text ? `${text[0].toUpperCase()}${text.slice(1)}` : text;
2739
+ }
2740
+
2741
+ function formatTurnstileToken(payload) {
2742
+ const lines = [
2743
+ "Turnstile token acquired",
2744
+ ` Token: ${payload.token ?? payload.tokenPreview ?? "-"}`,
2745
+ " Note: this token is short-lived and should be used immediately for one write operation.",
2746
+ ];
2747
+
2748
+ if (payload.backendBaseUrl) {
2749
+ lines.push(" Mode: hosted official Bangumi Turnstile");
2750
+ lines.push(` Backend: ${payload.backendBaseUrl}`);
2751
+ } else if (payload.verificationUrl) {
2752
+ lines.push(" Mode: local helper fallback");
2753
+ }
2754
+ if (payload.authorizeUrl) {
2755
+ lines.push(` Authorize URL: ${payload.authorizeUrl}`);
2756
+ }
2757
+ if (payload.redirectUri) {
2758
+ lines.push(` Callback URL: ${payload.redirectUri}`);
2759
+ }
2760
+ if (payload.sessionId) {
2761
+ lines.push(` Session ID: ${payload.sessionId}`);
2762
+ }
2763
+ if (payload.verificationUrl) {
2764
+ lines.push(` Helper URL: ${payload.verificationUrl}`);
2765
+ }
2766
+ if (payload.listenHost || payload.port !== undefined) {
2767
+ lines.push(` Listen address: ${payload.listenHost ?? "-"}:${payload.port ?? "-"}`);
2768
+ }
2769
+ lines.push(` Browser opened: ${payload.openedBrowser ? "yes" : "no"}`);
2770
+ lines.push(` Timeout: ${payload.timeoutSeconds ?? "-"} seconds`);
2771
+
2772
+ return lines.join("\n");
2773
+ }
2774
+
2775
+ function formatUser(user, context) {
2776
+ const title = context.rawArgs?.[1] === "me" ? "Current user" : "User";
2777
+ const lines = [
2778
+ title,
2779
+ ` Nickname: ${user.nickname ?? "-"}`,
2780
+ ` Username: ${user.username ?? "-"}`,
2781
+ ` User ID: ${user.id ?? "-"}`,
2782
+ ` Profile: ${user.url ?? "-"}`,
2783
+ ` User group: ${user.user_group ?? "-"}`,
2784
+ ];
2785
+
2786
+ if (user.sign) {
2787
+ lines.push(` Sign: ${user.sign}`);
2788
+ }
2789
+ if (user.email) {
2790
+ lines.push(` Email: ${user.email}`);
2791
+ }
2792
+ if (user.reg_time) {
2793
+ lines.push(` Registered: ${user.reg_time}`);
2794
+ }
2795
+ if (user.time_offset !== undefined) {
2796
+ lines.push(` Time offset: GMT${user.time_offset >= 0 ? "+" : ""}${user.time_offset}`);
2797
+ }
2798
+ if (user.avatar?.large) {
2799
+ lines.push(` Avatar: ${user.avatar.large}`);
2800
+ }
2801
+
2802
+ return lines.join("\n");
2803
+ }
2804
+
2805
+ function formatCalendar(payload) {
2806
+ const lines = [];
2807
+ for (const day of payload.data) {
2808
+ const weekday = day.weekday;
2809
+ if (lines.length > 0) {
2810
+ lines.push("");
2811
+ }
2812
+ lines.push(weekday.en);
2813
+ lines.push("");
2814
+ const items = day.items ?? [];
2815
+ if (items.length === 0) {
2816
+ lines.push(" (no items)");
2817
+ continue;
2818
+ }
2819
+ const rows = items.map((item) => {
2820
+ const name = item.name_cn || item.name;
2821
+ const score = item.rating?.score ?? "-";
2822
+ const doing = item.collection?.doing ?? 0;
2823
+ return {
2824
+ id: String(item.id),
2825
+ name: truncateDisplay(name, 40),
2826
+ score: score !== "-" ? String(score) : "-",
2827
+ doing: String(doing),
2828
+ };
2829
+ });
2830
+ lines.push(
2831
+ formatTable(rows, [
2832
+ { key: "id", header: "ID", minWidth: 8, maxWidth: 10 },
2833
+ { key: "name", header: "Name", minWidth: 20, maxWidth: 40 },
2834
+ { key: "score", header: "Score", minWidth: 5, maxWidth: 6 },
2835
+ { key: "doing", header: "Doing", minWidth: 5, maxWidth: 7 },
2836
+ ]),
2837
+ );
2838
+ }
2839
+ return lines.join("\n").trim();
2840
+ }
2841
+
2842
+ function formatSubject(subject, context = {}) {
2843
+ const verbose = Boolean(context?.verbose);
2844
+ const lines = [
2845
+ `Subject #${subject.id ?? "-"}`,
2846
+ ` Name: ${subject.name ?? "-"}`,
2847
+ ];
2848
+
2849
+ if (subject.name_cn) {
2850
+ lines.push(` Chinese name: ${subject.name_cn}`);
2851
+ }
2852
+
2853
+ lines.push(` Type: ${formatSubjectType(subject.type)}`);
2854
+
2855
+ if (subject.date) {
2856
+ lines.push(` Date: ${subject.date}`);
2857
+ }
2858
+ if (subject.platform) {
2859
+ lines.push(` Platform: ${subject.platform}`);
2860
+ }
2861
+ if (subject.eps || subject.total_episodes) {
2862
+ lines.push(` Episodes: ${subject.total_episodes ?? subject.eps ?? "-"}`);
2863
+ }
2864
+ if (subject.volumes) {
2865
+ lines.push(` Volumes: ${subject.volumes}`);
2866
+ }
2867
+ if (subject.rating?.score !== undefined) {
2868
+ lines.push(` Rating: ${subject.rating.score} (${subject.rating.total ?? 0} votes)`);
2869
+ }
2870
+ if (subject.rating?.rank) {
2871
+ lines.push(` Rank: #${subject.rating.rank}`);
2872
+ }
2873
+ if (subject.collection) {
2874
+ lines.push(
2875
+ ` Collections: collect ${subject.collection.collect ?? 0}, wish ${subject.collection.wish ?? 0}, doing ${subject.collection.doing ?? 0}, on_hold ${subject.collection.on_hold ?? 0}, dropped ${subject.collection.dropped ?? 0}`,
2876
+ );
2877
+ }
2878
+ if (subject.url) {
2879
+ lines.push(` URL: ${subject.url}`);
2880
+ } else if (subject.id) {
2881
+ lines.push(` URL: https://bgm.tv/subject/${subject.id}`);
2882
+ }
2883
+
2884
+ if (verbose) {
2885
+ if (subject.images) {
2886
+ lines.push("");
2887
+ lines.push("Images");
2888
+ if (subject.images.large) lines.push(` Large: ${subject.images.large}`);
2889
+ if (subject.images.medium) lines.push(` Medium: ${subject.images.medium}`);
2890
+ if (subject.images.common) lines.push(` Common: ${subject.images.common}`);
2891
+ }
2892
+
2893
+ if (Array.isArray(subject.infobox) && subject.infobox.length > 0) {
2894
+ lines.push("");
2895
+ lines.push(`Infobox (${subject.infobox.length} entries)`);
2896
+ for (const item of subject.infobox) {
2897
+ const key = item.key ?? "";
2898
+ const value = item.value;
2899
+ let displayValue;
2900
+ if (Array.isArray(value)) {
2901
+ displayValue = value
2902
+ .map((v) => (typeof v === "object" && v !== null ? v.v ?? "" : String(v)))
2903
+ .filter(Boolean)
2904
+ .join(", ");
2905
+ } else {
2906
+ displayValue = String(value ?? "");
2907
+ }
2908
+ if (displayValue) {
2909
+ lines.push(` ${key}: ${displayValue}`);
2910
+ }
2911
+ }
2912
+ }
2913
+
2914
+ if (Array.isArray(subject.tags) && subject.tags.length > 0) {
2915
+ lines.push("");
2916
+ lines.push("Tags");
2917
+ const topTags = subject.tags.slice(0, 15);
2918
+ for (const tag of topTags) {
2919
+ lines.push(` ${tag.name ?? "-"}: ${tag.count ?? 0}`);
2920
+ }
2921
+ }
2922
+
2923
+ if (subject.rating?.count) {
2924
+ lines.push("");
2925
+ lines.push("Rating Distribution");
2926
+ const counts = subject.rating.count;
2927
+ for (let score = 1; score <= 10; score += 1) {
2928
+ lines.push(` ${score}: ${counts[String(score)] ?? 0}`);
2929
+ }
2930
+ }
2931
+ }
2932
+
2933
+ if (subject.summary) {
2934
+ lines.push("");
2935
+ lines.push("Summary");
2936
+ lines.push(indentBlock(truncateText(subject.summary.trim(), verbose ? 800 : 400), 2));
2937
+ }
2938
+
2939
+ if (Array.isArray(subject.meta_tags) && subject.meta_tags.length > 0) {
2940
+ lines.push("");
2941
+ lines.push("Meta Tags");
2942
+ lines.push(` ${subject.meta_tags.slice(0, 10).join(", ")}`);
2943
+ }
2944
+
2945
+ return lines.join("\n");
2946
+ }
2947
+
2948
+ function formatPagedSubjects(payload) {
2949
+ const lines = [
2950
+ "Subjects",
2951
+ ` Range: ${payload.offset ?? 0}-${Math.min((payload.offset ?? 0) + (payload.data?.length ?? 0), payload.total ?? payload.data?.length ?? 0)} / ${payload.total ?? payload.data?.length ?? 0}`,
2952
+ ];
2953
+ const filters = payload.filters ?? {};
2954
+
2955
+ if (filters.mode === "search" && filters.keyword) {
2956
+ lines.push(` Keyword: ${filters.keyword}`);
2957
+ }
2958
+ if (filters.type !== undefined) {
2959
+ lines.push(` Type: ${filters.type ? formatSubjectType(filters.type) : "All"}`);
2960
+ }
2961
+ if (filters.sort) {
2962
+ lines.push(` Sort: ${filters.sort}`);
2963
+ }
2964
+ if (filters.year !== undefined && filters.year !== null) {
2965
+ lines.push(` Year: ${filters.year}`);
2966
+ }
2967
+ if (filters.month !== undefined && filters.month !== null) {
2968
+ lines.push(` Month: ${filters.month}`);
2969
+ }
2970
+ if (filters.platform) {
2971
+ lines.push(` Platform: ${filters.platform}`);
2972
+ }
2973
+ if (filters.cat) {
2974
+ lines.push(` Category: ${filters.cat}`);
2975
+ }
2976
+ if (filters.series !== undefined) {
2977
+ lines.push(` Series: ${filters.series ? "true" : "false"}`);
2978
+ }
2979
+ if (Array.isArray(filters.tag) && filters.tag.length > 0) {
2980
+ lines.push(` Tag: ${filters.tag.join(", ")}`);
2981
+ }
2982
+ if (Array.isArray(filters.metaTags) && filters.metaTags.length > 0) {
2983
+ lines.push(` Meta tags: ${filters.metaTags.join(", ")}`);
2984
+ }
2985
+ if (Array.isArray(filters.airDate) && filters.airDate.length > 0) {
2986
+ lines.push(` Air date: ${filters.airDate.join(", ")}`);
2987
+ }
2988
+ if (Array.isArray(filters.rating) && filters.rating.length > 0) {
2989
+ lines.push(` Rating filter: ${filters.rating.join(", ")}`);
2990
+ }
2991
+ if (Array.isArray(filters.ratingCount) && filters.ratingCount.length > 0) {
2992
+ lines.push(` Rating count: ${filters.ratingCount.join(", ")}`);
2993
+ }
2994
+ if (Array.isArray(filters.rank) && filters.rank.length > 0) {
2995
+ lines.push(` Rank filter: ${filters.rank.join(", ")}`);
2996
+ }
2997
+ if (filters.nsfw !== undefined) {
2998
+ lines.push(` NSFW: ${filters.nsfw ? "true" : "false"}`);
2999
+ }
3000
+
3001
+ const subjects = Array.isArray(payload.data) ? payload.data : [];
3002
+ if (subjects.length === 0) {
3003
+ lines.push("No results.");
3004
+ return lines.join("\n");
3005
+ }
3006
+
3007
+ const rows = subjects.map((subject) => ({
3008
+ id: subject.id ?? "-",
3009
+ name: subject.name_cn || subject.name || "-",
3010
+ type: formatSubjectType(subject.type),
3011
+ score: subject.rating?.score !== undefined ? String(subject.rating.score) : "",
3012
+ rank: subject.rating?.rank ? `#${subject.rating.rank}` : "",
3013
+ date: subject.date ?? "",
3014
+ }));
3015
+
3016
+ const table = formatTable(rows, [
3017
+ { key: "id", header: "#", minWidth: 6, align: "right" },
3018
+ { key: "name", header: "Name", minWidth: 8, maxWidth: 32, align: "left" },
3019
+ { key: "type", header: "Type", minWidth: 5, align: "left" },
3020
+ { key: "score", header: "Score", minWidth: 5, align: "right" },
3021
+ { key: "rank", header: "Rank", minWidth: 5, align: "right" },
3022
+ { key: "date", header: "Date", minWidth: 10, align: "left" },
3023
+ ]);
3024
+
3025
+ lines.push("");
3026
+ lines.push(table);
3027
+
3028
+ return lines.join("\n");
3029
+ }
3030
+
3031
+ function groupSubjectsByType(subjects) {
3032
+ const map = new Map();
3033
+
3034
+ for (const subject of subjects) {
3035
+ const type = Number(subject?.type ?? -1);
3036
+ if (!map.has(type)) {
3037
+ map.set(type, []);
3038
+ }
3039
+ map.get(type).push(subject);
3040
+ }
3041
+
3042
+ return [...map.entries()]
3043
+ .sort((left, right) => compareSubjectTypeOrder(left[0], right[0]))
3044
+ .map(([type, items]) => ({ type, items: sortSubjectsWithinType(items) }));
3045
+ }
3046
+
3047
+ function compareSubjectTypeOrder(left, right) {
3048
+ const leftIndex = SUBJECT_TYPE_ORDER.indexOf(left);
3049
+ const rightIndex = SUBJECT_TYPE_ORDER.indexOf(right);
3050
+ const normalizedLeft = leftIndex === -1 ? Number.MAX_SAFE_INTEGER : leftIndex;
3051
+ const normalizedRight = rightIndex === -1 ? Number.MAX_SAFE_INTEGER : rightIndex;
3052
+
3053
+ if (normalizedLeft !== normalizedRight) {
3054
+ return normalizedLeft - normalizedRight;
3055
+ }
3056
+
3057
+ return left - right;
3058
+ }
3059
+
3060
+ function sortSubjectsWithinType(subjects) {
3061
+ return [...subjects].sort((left, right) => {
3062
+ const leftRank = Number(left?.rating?.rank ?? left?.rank ?? Number.MAX_SAFE_INTEGER);
3063
+ const rightRank = Number(right?.rating?.rank ?? right?.rank ?? Number.MAX_SAFE_INTEGER);
3064
+
3065
+ if (leftRank !== rightRank) {
3066
+ return leftRank - rightRank;
3067
+ }
3068
+
3069
+ const leftScore = Number(left?.rating?.score ?? -1);
3070
+ const rightScore = Number(right?.rating?.score ?? -1);
3071
+ if (leftScore !== rightScore) {
3072
+ return rightScore - leftScore;
3073
+ }
3074
+
3075
+ const leftName = String(left?.name_cn || left?.name || "");
3076
+ const rightName = String(right?.name_cn || right?.name || "");
3077
+ return leftName.localeCompare(rightName, "zh-Hans-CN");
3078
+ });
3079
+ }
3080
+
3081
+ function formatConfigValue(key, value) {
3082
+ if (value === undefined || value === null || value === "") {
3083
+ return "-";
3084
+ }
3085
+
3086
+ const sensitiveKeys = new Set([
3087
+ "accessToken",
3088
+ "refreshToken",
3089
+ "clientSecret",
3090
+ "privateSessionId",
3091
+ "tokenType",
3092
+ ]);
3093
+
3094
+ if (sensitiveKeys.has(key)) {
3095
+ if (key === "tokenType") {
3096
+ return String(value);
3097
+ }
3098
+ return maskToken(String(value));
3099
+ }
3100
+
3101
+ if (key === "timezone") {
3102
+ return `${String(value)} (${formatTimezoneOffset(String(value))})`;
3103
+ }
3104
+
3105
+ if (key === "proxy") {
3106
+ return formatProxyUrl(value);
3107
+ }
3108
+
3109
+ return String(value);
3110
+ }
3111
+
3112
+ function formatProxyUrl(value) {
3113
+ const raw = String(value);
3114
+ try {
3115
+ const url = new URL(raw);
3116
+ if (url.username || url.password) {
3117
+ url.username = "****";
3118
+ if (url.password) {
3119
+ url.password = "****";
3120
+ }
3121
+ }
3122
+ return url.toString().replace(/\/+$/, "");
3123
+ } catch {
3124
+ return raw.replace(/\/\/([^:@/\s]+):([^@/\s]+)@/, "//****:****@");
3125
+ }
3126
+ }
3127
+
3128
+ function maskToken(token) {
3129
+ if (!token) {
3130
+ return "-";
3131
+ }
3132
+
3133
+ const value = String(token);
3134
+ if (value.length <= 10) {
3135
+ return `${value.slice(0, 2)}***`;
3136
+ }
3137
+
3138
+ return `${value.slice(0, 6)}...${value.slice(-4)}`;
3139
+ }
3140
+
3141
+ function truncateText(text, maxLength) {
3142
+ if (text.length <= maxLength) {
3143
+ return text;
3144
+ }
3145
+
3146
+ return `${text.slice(0, maxLength).trimEnd()}...`;
3147
+ }
3148
+
3149
+ function indentBlock(text, spaces = 2) {
3150
+ const prefix = " ".repeat(spaces);
3151
+ return String(text)
3152
+ .split("\n")
3153
+ .map((line) => `${prefix}${line}`)
3154
+ .join("\n");
3155
+ }
3156
+
3157
+ function formatTimestamp(value) {
3158
+ if (!value) {
3159
+ return "-";
3160
+ }
3161
+
3162
+ const date = parseTimestampValue(value);
3163
+ if (Number.isNaN(date.getTime())) {
3164
+ return String(value);
3165
+ }
3166
+
3167
+ const timezone = getConfig().timezone;
3168
+ const parts = new Intl.DateTimeFormat("en-CA", {
3169
+ timeZone: timezone,
3170
+ year: "numeric",
3171
+ month: "2-digit",
3172
+ day: "2-digit",
3173
+ hour: "2-digit",
3174
+ minute: "2-digit",
3175
+ second: "2-digit",
3176
+ hour12: false,
3177
+ }).formatToParts(date);
3178
+ const lookup = Object.fromEntries(parts.filter((part) => part.type !== "literal").map((part) => [part.type, part.value]));
3179
+
3180
+ return `${lookup.year}-${lookup.month}-${lookup.day} ${lookup.hour}:${lookup.minute}:${lookup.second} ${formatTimezoneLabel(timezone)}`;
3181
+ }
3182
+
3183
+ function parseTimestampValue(value) {
3184
+ if (value instanceof Date) {
3185
+ return value;
3186
+ }
3187
+
3188
+ if (typeof value === "number") {
3189
+ return new Date(value * 1000);
3190
+ }
3191
+
3192
+ if (typeof value === "string") {
3193
+ const trimmed = value.trim();
3194
+ if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
3195
+ return new Date(Number(trimmed) * 1000);
3196
+ }
3197
+
3198
+ return new Date(trimmed);
3199
+ }
3200
+
3201
+ return new Date(Number(value) * 1000);
3202
+ }
3203
+
3204
+ function formatTimezoneLabel(timezone) {
3205
+ if (timezone === "Asia/Shanghai") {
3206
+ return "CST (UTC+08:00)";
3207
+ }
3208
+
3209
+ return formatTimezoneOffset(timezone);
3210
+ }
3211
+
3212
+ function formatTimezoneOffset(timezone) {
3213
+ try {
3214
+ const parts = new Intl.DateTimeFormat("en-US", {
3215
+ timeZone: timezone,
3216
+ timeZoneName: "shortOffset",
3217
+ }).formatToParts(new Date());
3218
+ const zoneName = parts.find((part) => part.type === "timeZoneName")?.value ?? timezone;
3219
+ return zoneName.replace(/^GMT/i, "UTC").replace(/^(UTC[+-])(\d{1,2})$/, "$10$2:00");
3220
+ } catch {
3221
+ return timezone;
3222
+ }
3223
+ }
3224
+
3225
+ function formatPageRange(offsetValue, lengthValue, totalValue) {
3226
+ const offset = Number(offsetValue ?? 0);
3227
+ const length = Number(lengthValue ?? 0);
3228
+ const total = totalValue ?? length;
3229
+ return `${offset}-${Math.min(offset + length, total)} / ${total}`;
3230
+ }
3231
+
3232
+ function formatHotScore(value) {
3233
+ return Number(value ?? 0).toFixed(4);
3234
+ }
3235
+
3236
+ function formatSubjectType(type) {
3237
+ return SUBJECT_TYPE_LABELS[type] ?? String(type ?? "-");
3238
+ }
3239
+
3240
+ function formatEpisodeType(type) {
3241
+ return EPISODE_TYPE_LABELS[type] ?? String(type ?? "-");
3242
+ }
3243
+
3244
+ function formatEpisodeTypeFilter(type) {
3245
+ if (type === undefined || type === null || type === "") {
3246
+ return "All";
3247
+ }
3248
+ if (type === "op_ed") {
3249
+ return "OP/ED";
3250
+ }
3251
+ return formatEpisodeType(type);
3252
+ }
3253
+
3254
+ function formatEpisodeNumber(episode) {
3255
+ if (!isObject(episode)) {
3256
+ return "";
3257
+ }
3258
+ if (Number(episode.type) === 0 && episode.ep !== undefined && episode.ep !== null) {
3259
+ return `EP ${episode.ep}`;
3260
+ }
3261
+ if (episode.sort !== undefined && episode.sort !== null) {
3262
+ return `Sort ${episode.sort}`;
3263
+ }
3264
+ return "";
3265
+ }
3266
+
3267
+ function formatCollectionStatus(type) {
3268
+ return COLLECTION_STATUS_LABELS[type] ?? String(type ?? "-");
3269
+ }
3270
+
3271
+ function formatEpisodeCollectionStatus(type) {
3272
+ return EPISODE_COLLECTION_STATUS_LABELS[type] ?? String(type ?? "-");
3273
+ }
3274
+
3275
+ function formatGroupMemberRole(role) {
3276
+ if (role === undefined || role === null || role === "") {
3277
+ return "All";
3278
+ }
3279
+
3280
+ return GROUP_MEMBER_ROLE_LABELS[role] ?? String(role);
3281
+ }
3282
+
3283
+ function formatTimelineCat(cat) {
3284
+ return TIMELINE_CAT_LABELS[cat] ?? String(cat ?? "-");
3285
+ }
3286
+
3287
+ function formatTimelineLine(entry) {
3288
+ const pieces = [
3289
+ `#${entry.id ?? "-"}`,
3290
+ `[${formatTimelineCat(entry.cat)}]`,
3291
+ ];
3292
+
3293
+ if (entry.user || entry.uid) {
3294
+ pieces.push(`by ${formatUserLabel(entry.user, entry.uid)}`);
3295
+ }
3296
+ pieces.push(`${entry.replies ?? 0} replies`);
3297
+ if (entry.createdAt) {
3298
+ pieces.push(formatTimestamp(entry.createdAt));
3299
+ }
3300
+
3301
+ return pieces.join(" ");
3302
+ }
3303
+
3304
+ function formatTimelineMemoSummary(memo) {
3305
+ if (!isObject(memo)) {
3306
+ return "";
3307
+ }
3308
+
3309
+ if (memo.status?.tsukkomi) {
3310
+ return memo.status.tsukkomi;
3311
+ }
3312
+ if (memo.status?.sign) {
3313
+ return `Sign: ${memo.status.sign}`;
3314
+ }
3315
+ if (memo.status?.nickname) {
3316
+ return `Nickname: ${memo.status.nickname.before ?? "-"} -> ${memo.status.nickname.after ?? "-"}`;
3317
+ }
3318
+ if (memo.blog?.title) {
3319
+ return `Blog: ${memo.blog.title}`;
3320
+ }
3321
+ if (memo.index?.title) {
3322
+ return `Index: ${memo.index.title}`;
3323
+ }
3324
+ if (Array.isArray(memo.subject) && memo.subject.length > 0) {
3325
+ const names = memo.subject
3326
+ .map((item) => formatSlimSubjectLabel(item?.subject))
3327
+ .filter(Boolean)
3328
+ .slice(0, 3);
3329
+ if (names.length > 0) {
3330
+ return `Subjects: ${names.join(" | ")}`;
3331
+ }
3332
+ }
3333
+ if (memo.progress?.single?.subject || memo.progress?.single?.episode) {
3334
+ const subject = formatSlimSubjectLabel(memo.progress.single.subject);
3335
+ const episode = memo.progress.single.episode;
3336
+ const episodeLabel = episode ? `EP ${episode.sort ?? episode.id ?? "-"} ${episode.nameCN || episode.name || ""}`.trim() : "";
3337
+ return ["Progress:", subject, episodeLabel].filter(Boolean).join(" ");
3338
+ }
3339
+ if (memo.progress?.batch?.subject) {
3340
+ const subject = formatSlimSubjectLabel(memo.progress.batch.subject);
3341
+ const updates = [];
3342
+ if (memo.progress.batch.epsUpdate) {
3343
+ updates.push(`+${memo.progress.batch.epsUpdate} eps`);
3344
+ }
3345
+ if (memo.progress.batch.volsUpdate) {
3346
+ updates.push(`+${memo.progress.batch.volsUpdate} vols`);
3347
+ }
3348
+ return ["Progress:", subject, updates.join(" ")].filter(Boolean).join(" ");
3349
+ }
3350
+ if (memo.wiki?.subject) {
3351
+ return `Wiki: ${formatSlimSubjectLabel(memo.wiki.subject)}`;
3352
+ }
3353
+ if (memo.daily?.users || memo.daily?.groups) {
3354
+ const users = Array.isArray(memo.daily.users) ? memo.daily.users.map((user) => formatUserLabel(user)).filter(Boolean) : [];
3355
+ const groups = Array.isArray(memo.daily.groups)
3356
+ ? memo.daily.groups.map((group) => group?.title || group?.name).filter(Boolean)
3357
+ : [];
3358
+ return [
3359
+ users.length > 0 ? `Users: ${users.slice(0, 3).join(", ")}` : "",
3360
+ groups.length > 0 ? `Groups: ${groups.slice(0, 3).join(", ")}` : "",
3361
+ ]
3362
+ .filter(Boolean)
3363
+ .join(" | ");
3364
+ }
3365
+ if (memo.mono?.characters || memo.mono?.persons) {
3366
+ const characters = Array.isArray(memo.mono.characters)
3367
+ ? memo.mono.characters.map((character) => character?.nameCN || character?.name).filter(Boolean)
3368
+ : [];
3369
+ const persons = Array.isArray(memo.mono.persons)
3370
+ ? memo.mono.persons.map((person) => person?.nameCN || person?.name).filter(Boolean)
3371
+ : [];
3372
+ return [
3373
+ characters.length > 0 ? `Characters: ${characters.slice(0, 3).join(", ")}` : "",
3374
+ persons.length > 0 ? `Persons: ${persons.slice(0, 3).join(", ")}` : "",
3375
+ ]
3376
+ .filter(Boolean)
3377
+ .join(" | ");
3378
+ }
3379
+
3380
+ return "";
3381
+ }
3382
+
3383
+ function formatTimelineSource(source) {
3384
+ if (!isObject(source)) {
3385
+ return "-";
3386
+ }
3387
+
3388
+ const pieces = [];
3389
+ if (source.name) {
3390
+ pieces.push(source.name);
3391
+ }
3392
+ if (source.url) {
3393
+ pieces.push(source.url);
3394
+ }
3395
+ return pieces.join(" ") || "-";
3396
+ }
3397
+
3398
+ function formatSlimSubjectLabel(subject) {
3399
+ if (!isObject(subject)) {
3400
+ return "";
3401
+ }
3402
+
3403
+ const name = subject.nameCN || subject.name;
3404
+ if (!name) {
3405
+ return subject.id ? `#${subject.id}` : "";
3406
+ }
3407
+
3408
+ return subject.id ? `#${subject.id} ${name}` : name;
3409
+ }
3410
+
3411
+ function formatUserLabel(user, fallbackId) {
3412
+ if (!isObject(user)) {
3413
+ return fallbackId ? `#${fallbackId}` : "-";
3414
+ }
3415
+
3416
+ const pieces = [];
3417
+ if (user.nickname) {
3418
+ pieces.push(user.nickname);
3419
+ }
3420
+ if (user.username) {
3421
+ pieces.push(`@${user.username}`);
3422
+ } else if (user.id ?? fallbackId) {
3423
+ pieces.push(`#${user.id ?? fallbackId}`);
3424
+ }
3425
+ return pieces.join(" ") || "-";
3426
+ }
3427
+
3428
+ function formatTopicLine(topic) {
3429
+ const pieces = [
3430
+ `#${topic.id ?? "-"}`,
3431
+ topic.title ?? "-",
3432
+ ];
3433
+
3434
+ if (topic.group?.title) {
3435
+ pieces.push(`[${topic.group.title}]`);
3436
+ }
3437
+ if (topic.replyCount !== undefined) {
3438
+ pieces.push(`${topic.replyCount} replies`);
3439
+ }
3440
+ if (topic.creator || topic.creatorID) {
3441
+ pieces.push(`by ${formatUserLabel(topic.creator, topic.creatorID)}`);
3442
+ }
3443
+ if (topic.updatedAt) {
3444
+ pieces.push(`updated ${formatTimestamp(topic.updatedAt)}`);
3445
+ }
3446
+
3447
+ return pieces.join(" ");
3448
+ }
3449
+
3450
+ function formatReplyLine(reply) {
3451
+ const pieces = [
3452
+ `#${reply.id ?? "-"}`,
3453
+ `by ${formatUserLabel(reply.creator, reply.creatorID)}`,
3454
+ ];
3455
+
3456
+ if (reply.createdAt) {
3457
+ pieces.push(formatTimestamp(reply.createdAt));
3458
+ }
3459
+
3460
+ return pieces.join(" ");
3461
+ }
3462
+
3463
+ function formatBlogCommentLine(comment) {
3464
+ const pieces = [
3465
+ `#${comment.id ?? "-"}`,
3466
+ `by ${formatUserLabel(comment.user, comment.creatorID)}`,
3467
+ ];
3468
+
3469
+ if (comment.createdAt) {
3470
+ pieces.push(formatTimestamp(comment.createdAt));
3471
+ }
3472
+ if (comment.relatedID) {
3473
+ pieces.push(`reply to #${comment.relatedID}`);
3474
+ }
3475
+
3476
+ return pieces.join(" ");
3477
+ }
3478
+
3479
+ function appendCommentTree(lines, comments, emptyMessage) {
3480
+ const list = Array.isArray(comments) ? comments : [];
3481
+ if (list.length === 0) {
3482
+ lines.push(emptyMessage);
3483
+ return;
3484
+ }
3485
+
3486
+ for (const comment of list) {
3487
+ lines.push("");
3488
+ lines.push(`• ${formatBlogCommentLine(comment)}`);
3489
+ if (comment.content) {
3490
+ lines.push(indentBlock(truncateText(String(comment.content).trim(), 800), 2));
3491
+ }
3492
+
3493
+ const replies = Array.isArray(comment.replies) ? comment.replies : [];
3494
+ for (const reply of replies) {
3495
+ lines.push(` - ${formatBlogCommentLine(reply)}`);
3496
+ if (reply.content) {
3497
+ lines.push(indentBlock(truncateText(String(reply.content).trim(), 500), 4));
3498
+ }
3499
+ }
3500
+ }
3501
+ }
3502
+
3503
+ function isConfigShowPayload(value) {
3504
+ return isObject(value) && "configFile" in value && "config" in value;
3505
+ }
3506
+
3507
+ function isConfigMutationPayload(value) {
3508
+ return isObject(value) && "configFile" in value && ("updated" in value || "removed" in value);
3509
+ }
3510
+
3511
+ function isProxyShowPayload(value) {
3512
+ return isObject(value) && isObject(value.proxy) && "source" in value.proxy && "active" in value.proxy;
3513
+ }
3514
+
3515
+ function formatProxyShow(payload) {
3516
+ const { url, source, active } = payload.proxy;
3517
+ if (!url) {
3518
+ return "Proxy: not set";
3519
+ }
3520
+ return [
3521
+ "Proxy",
3522
+ ` URL: ${formatProxyUrl(url)}`,
3523
+ ` Source: ${source}`,
3524
+ ` Active: ${active ? "yes" : "no"}`,
3525
+ ].join("\n");
3526
+ }
3527
+
3528
+ function isVersionStatusPayload(value) {
3529
+ return isObject(value) && value.resource === "version-status";
3530
+ }
3531
+
3532
+ function isInstallPathPayload(value) {
3533
+ return isObject(value)
3534
+ && ["install-path", "update"].includes(value.action)
3535
+ && ("configFile" in value || "platform" in value || "repoDir" in value || "installDir" in value);
3536
+ }
3537
+
3538
+ function isLoginUrlPayload(value) {
3539
+ return isObject(value) && typeof value.loginUrl === "string" && !("resource" in value);
3540
+ }
3541
+
3542
+ function isTokenSetPayload(value) {
3543
+ return isObject(value) && "saved" in value && "accessTokenPreview" in value;
3544
+ }
3545
+
3546
+ function isAuthStatusPayload(value) {
3547
+ return isObject(value) && value.resource === "auth-status" && isObject(value.channels);
3548
+ }
3549
+
3550
+ function isTokenStatusPayload(value) {
3551
+ return isObject(value) && (("client_id" in value && "expires" in value) || value.resource === "access-token-status");
3552
+ }
3553
+
3554
+ function isPrivateSessionMutationPayload(value) {
3555
+ return isObject(value) && value.resource === "private-session-mutation" && typeof value.sessionPreview === "string";
3556
+ }
3557
+
3558
+ function isPrivateSessionStatusPayload(value) {
3559
+ return isObject(value) && value.resource === "private-session-status" && typeof value.saved === "boolean";
3560
+ }
3561
+
3562
+ function isAuthLoginPayload(value) {
3563
+ return isObject(value) && value.resource === "auth-login" && isObject(value.user);
3564
+ }
3565
+
3566
+ function isAuthLogoutPayload(value) {
3567
+ return isObject(value) && value.resource === "auth-logout";
3568
+ }
3569
+
3570
+ function isAuthClearPayload(value) {
3571
+ return isObject(value) && value.resource === "auth-clear" && Array.isArray(value.cleared);
3572
+ }
3573
+
3574
+ function isStatusIncidentsPayload(value) {
3575
+ return isObject(value) && value.resource === "status-incidents" && Array.isArray(value.data);
3576
+ }
3577
+
3578
+ function isStatusCurrentPayload(value) {
3579
+ return isObject(value) && value.resource === "status-current" && Array.isArray(value.affectedComponents);
3580
+ }
3581
+
3582
+ function isNotificationListPayload(value) {
3583
+ return isObject(value) && value.resource === "notifications" && Array.isArray(value.data);
3584
+ }
3585
+
3586
+ function isNotificationClearPayload(value) {
3587
+ return isObject(value) && value.resource === "notification-clear";
3588
+ }
3589
+
3590
+ function isCollectionListPayload(value) {
3591
+ return (
3592
+ isObject(value) &&
3593
+ Array.isArray(value.data) &&
3594
+ isObject(value.filters) &&
3595
+ value.title === undefined &&
3596
+ ("user" in value.filters || "status" in value.filters || "subjectType" in value.filters || "order" in value.filters)
3597
+ );
3598
+ }
3599
+
3600
+ function isCollectionMutationPayload(value) {
3601
+ return isObject(value) && typeof value.action === "string" && "subjectId" in value && value.resource !== "episode-mutation";
3602
+ }
3603
+
3604
+ function isEpisodeListPayload(value) {
3605
+ return isObject(value) && value.resource === "episode-list" && Array.isArray(value.data);
3606
+ }
3607
+
3608
+ function isEpisodeMutationPayload(value) {
3609
+ return isObject(value) && value.resource === "episode-mutation" && typeof value.action === "string";
3610
+ }
3611
+
3612
+ function isEpisodeCommentsPayload(value) {
3613
+ return isObject(value) && value.resource === "episode-comments" && Array.isArray(value.data);
3614
+ }
3615
+
3616
+ function isEpisodeCommentMutationPayload(value) {
3617
+ return isObject(value) && value.resource === "episode-comment-mutation" && typeof value.action === "string";
3618
+ }
3619
+
3620
+ function isBlogListPayload(value) {
3621
+ return isObject(value) && value.resource === "blog-list" && Array.isArray(value.data);
3622
+ }
3623
+
3624
+ function isIndexPayload(value) {
3625
+ return isObject(value) && "title" in value && "desc" in value && "collects" in value && "stats" in value && "replies" in value;
3626
+ }
3627
+
3628
+ function isIndexCommentsPayload(value) {
3629
+ return isObject(value) && value.resource === "index-comments" && Array.isArray(value.data);
3630
+ }
3631
+
3632
+ function isIndexRelatedPayload(value) {
3633
+ return isObject(value) && value.resource === "index-related" && Array.isArray(value.data);
3634
+ }
3635
+
3636
+ function isIndexMutationPayload(value) {
3637
+ return isObject(value) && value.resource === "index-mutation" && typeof value.action === "string";
3638
+ }
3639
+
3640
+ function isIndexCommentMutationPayload(value) {
3641
+ return isObject(value) && value.resource === "index-comment-mutation" && typeof value.action === "string";
3642
+ }
3643
+
3644
+ function isIndexRelatedMutationPayload(value) {
3645
+ return isObject(value) && value.resource === "index-related-mutation" && typeof value.action === "string";
3646
+ }
3647
+
3648
+ function isBlogCommentsPayload(value) {
3649
+ return isObject(value) && value.resource === "blog-comments" && Array.isArray(value.data);
3650
+ }
3651
+
3652
+ function isBlogPhotosPayload(value) {
3653
+ return isObject(value) && value.resource === "blog-photos" && Array.isArray(value.data);
3654
+ }
3655
+
3656
+ function isBlogSubjectsPayload(value) {
3657
+ return isObject(value) && value.resource === "blog-subjects" && Array.isArray(value.data);
3658
+ }
3659
+
3660
+ function isBlogCommentMutationPayload(value) {
3661
+ return isObject(value) && value.resource === "blog-comment-mutation" && typeof value.action === "string";
3662
+ }
3663
+
3664
+ function isBlogPayload(value) {
3665
+ return isObject(value) && "title" in value && "content" in value && "views" in value && "public" in value && "user" in value;
3666
+ }
3667
+
3668
+ function isTimelineListPayload(value) {
3669
+ return isObject(value) && ["timeline-list", "timeline-user-list"].includes(value.resource) && Array.isArray(value.data);
3670
+ }
3671
+
3672
+ function isTimelineEventsPayload(value) {
3673
+ return isObject(value) && value.resource === "timeline-events" && Array.isArray(value.data);
3674
+ }
3675
+
3676
+ function isTimelineRepliesPayload(value) {
3677
+ return isObject(value) && value.resource === "timeline-replies" && Array.isArray(value.data);
3678
+ }
3679
+
3680
+ function isTimelineMutationPayload(value) {
3681
+ return isObject(value) && value.resource === "timeline-mutation" && typeof value.action === "string";
3682
+ }
3683
+
3684
+ function isGroupListPayload(value) {
3685
+ return isObject(value) && value.resource === "group-list" && Array.isArray(value.data);
3686
+ }
3687
+
3688
+ function isGroupHotPayload(value) {
3689
+ return isObject(value) && value.resource === "group-hot" && Array.isArray(value.data);
3690
+ }
3691
+
3692
+ function isGroupHotTopicsPayload(value) {
3693
+ return isObject(value) && value.resource === "group-hot-topics" && Array.isArray(value.data);
3694
+ }
3695
+
3696
+ function isGroupLatestRepliesPayload(value) {
3697
+ return isObject(value) && value.resource === "group-latest-replies" && Array.isArray(value.data);
3698
+ }
3699
+
3700
+ function isGroupMembersPayload(value) {
3701
+ return isObject(value) && value.resource === "group-members" && Array.isArray(value.data);
3702
+ }
3703
+
3704
+ function isGroupTopicsPayload(value) {
3705
+ return isObject(value) && ["group-topics", "group-recent-topics"].includes(value.resource) && Array.isArray(value.data);
3706
+ }
3707
+
3708
+ function isGroupPayload(value) {
3709
+ return isObject(value) && "title" in value && "members" in value && "topics" in value && "posts" in value && "accessible" in value;
3710
+ }
3711
+
3712
+ function isGroupTopicPayload(value) {
3713
+ return isObject(value) && "title" in value && "parentID" in value && "replyCount" in value && "updatedAt" in value && "group" in value && "replies" in value;
3714
+ }
3715
+
3716
+ function isSubjectTopicPayload(value) {
3717
+ return isObject(value) && "title" in value && "parentID" in value && "replyCount" in value && "updatedAt" in value && "subject" in value && "replies" in value;
3718
+ }
3719
+
3720
+ function isGroupTopicMutationPayload(value) {
3721
+ return isObject(value) && value.resource === "group-topic-mutation" && typeof value.action === "string";
3722
+ }
3723
+
3724
+ function isTopicMutationPayload(value) {
3725
+ return isObject(value) && value.resource === "topic-mutation" && typeof value.action === "string";
3726
+ }
3727
+
3728
+ function isTopicPostPayload(value) {
3729
+ return isObject(value) && value.resource === "topic-post" && isObject(value.data);
3730
+ }
3731
+
3732
+ function isPostMutationPayload(value) {
3733
+ return isObject(value) && value.resource === "post-mutation" && typeof value.action === "string";
3734
+ }
3735
+
3736
+ function isSubjectCollectMutationPayload(value) {
3737
+ return isObject(value) && value.resource === "subject-collect-mutation" && typeof value.action === "string";
3738
+ }
3739
+
3740
+ function isMonoCommentMutationPayload(value) {
3741
+ return isObject(value) && value.resource === "mono-comment-mutation" && typeof value.action === "string";
3742
+ }
3743
+
3744
+ function isMonoPhotoPayload(value) {
3745
+ return isObject(value) && value.resource === "mono-photo" && isObject(value.data);
3746
+ }
3747
+
3748
+ function isMonoPhotoCommentsPayload(value) {
3749
+ return isObject(value) && value.resource === "mono-photo-comments" && Array.isArray(value.data);
3750
+ }
3751
+
3752
+ function isSimpleCollectionMutationPayload(value) {
3753
+ return isObject(value) && value.resource === "simple-collection-mutation" && typeof value.action === "string";
3754
+ }
3755
+
3756
+ function isTurnstileTokenPayload(value) {
3757
+ return isObject(value) && value.resource === "turnstile-token" && typeof value.token === "string";
3758
+ }
3759
+
3760
+ function isOAuthTokenPayload(value) {
3761
+ return isObject(value) && "access_token" in value && ("refresh_token" in value || "expires_in" in value);
3762
+ }
3763
+
3764
+ function isMonoDetailPayload(value) {
3765
+ return isObject(value)
3766
+ && ["character", "person"].includes(value.resource)
3767
+ && isObject(value.data);
3768
+ }
3769
+
3770
+ function isGenericP1ListPayload(value) {
3771
+ return isObject(value)
3772
+ && typeof value.resource === "string"
3773
+ && typeof value.title === "string"
3774
+ && Array.isArray(value.data);
3775
+ }
3776
+
3777
+ function isUserPayload(value) {
3778
+ return isObject(value) && "id" in value && "username" in value && "nickname" in value;
3779
+ }
3780
+
3781
+ function isPagedSubjectPayload(value) {
3782
+ return isObject(value) && Array.isArray(value.data) && ("total" in value || "limit" in value || "filters" in value);
3783
+ }
3784
+
3785
+ function isSubjectPayload(value) {
3786
+ return isObject(value) && "id" in value && "name" in value && "type" in value;
3787
+ }
3788
+
3789
+ function isCalendarPayload(value) {
3790
+ return isObject(value) && value.resource === "calendar" && Array.isArray(value.data);
3791
+ }
3792
+
3793
+ function isObject(value) {
3794
+ return typeof value === "object" && value !== null;
3795
+ }
3796
+
3797
+ // ── Table formatting (CJK-safe) ────────────────────────────────
3798
+
3799
+ function displayWidth(str) {
3800
+ let width = 0;
3801
+ for (const char of String(str)) {
3802
+ const cp = char.codePointAt(0);
3803
+ if (
3804
+ (cp >= 0x2E80 && cp <= 0x9FFF) ||
3805
+ (cp >= 0xAC00 && cp <= 0xD7FF) ||
3806
+ (cp >= 0xF900 && cp <= 0xFAFF) ||
3807
+ (cp >= 0xFE30 && cp <= 0xFE6F) ||
3808
+ (cp >= 0xFF00 && cp <= 0xFFEF) ||
3809
+ (cp >= 0x20000 && cp <= 0x2FA1F)
3810
+ ) {
3811
+ width += 2;
3812
+ } else {
3813
+ width += 1;
3814
+ }
3815
+ }
3816
+ return width;
3817
+ }
3818
+
3819
+ function padDisplay(str, targetWidth, align = "left") {
3820
+ const strW = displayWidth(str);
3821
+ const pad = targetWidth - strW;
3822
+ if (pad <= 0) return str;
3823
+ const spaces = " ".repeat(pad);
3824
+ return align === "right" ? spaces + str : str + spaces;
3825
+ }
3826
+
3827
+ function truncateDisplay(str, maxWidth) {
3828
+ const totalW = displayWidth(str);
3829
+ if (totalW <= maxWidth) return str;
3830
+
3831
+ let result = "";
3832
+ let w = 0;
3833
+ for (const char of String(str)) {
3834
+ const cw = displayWidth(char);
3835
+ if (w + cw > maxWidth - 1) {
3836
+ result += "…";
3837
+ break;
3838
+ }
3839
+ result += char;
3840
+ w += cw;
3841
+ }
3842
+ return result;
3843
+ }
3844
+
3845
+ function formatTable(rows, columns) {
3846
+ // columns: [{ key, header, minWidth, maxWidth, align }]
3847
+ const widths = columns.map((col) => {
3848
+ const headerW = displayWidth(col.header);
3849
+ const maxDataW = rows.reduce((max, row) => {
3850
+ const cell = String(row[col.key] ?? "");
3851
+ return Math.max(max, displayWidth(cell));
3852
+ }, 0);
3853
+ let w = Math.max(headerW, maxDataW, col.minWidth ?? 3) + 2;
3854
+ if (col.maxWidth) {
3855
+ w = Math.min(w, col.maxWidth + 2);
3856
+ }
3857
+ return w;
3858
+ });
3859
+
3860
+ // Build lines
3861
+ const lines = [];
3862
+
3863
+ // Header
3864
+ const headerLine = columns
3865
+ .map((col, i) => " " + padDisplay(col.header, widths[i] - 2, col.align ?? "left") + " ")
3866
+ .join("│");
3867
+ lines.push("│" + headerLine + "│");
3868
+
3869
+ // Separator
3870
+ const sepLine = widths.map((w) => "─".repeat(w)).join("┼");
3871
+ lines.push("├" + sepLine + "┤");
3872
+
3873
+ // Rows
3874
+ for (const row of rows) {
3875
+ const cells = columns.map((col, i) => {
3876
+ const raw = String(row[col.key] ?? "");
3877
+ const truncated = truncateDisplay(raw, widths[i] - 2);
3878
+ return " " + padDisplay(truncated, widths[i] - 2, col.align ?? "left") + " ";
3879
+ });
3880
+ lines.push("│" + cells.join("│") + "│");
3881
+ }
3882
+
3883
+ // Bottom border
3884
+ const bottomLine = widths.map((w) => "─".repeat(w)).join("┴");
3885
+ lines.push("└" + bottomLine + "┘");
3886
+
3887
+ return lines.join("\n");
3888
+ }