@aronnaxlin/bgm-cli 1.0.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -15,8 +15,8 @@
15
15
  npm / npx:
16
16
 
17
17
  ```bash
18
- npx @aronnax/bgm-cli --help
19
- npm install -g @aronnax/bgm-cli
18
+ npx @aronnaxlin/bgm-cli --help
19
+ npm install -g @aronnaxlin/bgm-cli
20
20
  ```
21
21
 
22
22
  macOS / Linux:
@@ -80,9 +80,12 @@ bgm character search "Asuka" --limit 3
80
80
  bgm person search "Anno" --limit 3
81
81
  bgm collection get 348335
82
82
  bgm collection indexes --user sai --limit 5
83
+ bgm book get 3510
84
+ bgm book ep 3510 10
83
85
  bgm group list --sort members --limit 10
84
86
  bgm group user sai --limit 5
85
87
  bgm index user sai --limit 5
88
+ bgm search subject "One Piece" --limit 5
86
89
  bgm trending subjects --type anime --limit 5
87
90
  bgm --json user me
88
91
  ```
@@ -114,8 +117,9 @@ Detailed split documentation is currently maintained in Simplified Chinese under
114
117
  - Thanks to [`bgm.tv`](https://bgm.tv/) for the main Bangumi site and community ecosystem.
115
118
  - Thanks to [`bangumi/server-private`](https://github.com/bangumi/server-private) for private API implementation references.
116
119
  - Thanks to [`bangumi/api`](https://github.com/bangumi/api) for public API implementation and documentation foundations.
117
- - Thanks to [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) for the community-run Bangumi availability status service used by this feature; the service author is [`wataame`](https://bangumi.tv/user/wataame).
118
- - This repository tries to reflect currently verifiable Bangumi behavior, but it does not promise full website feature coverage or long-term stability of third-party behaviors.
120
+ - Thanks to [`SearchEncore`](https://bgmdb.ry.mk/v1/docs) (`bgmdb.ry.mk`) for the community-maintained Bangumi enhanced search capability; the service author is [`wataame`](https://bangumi.tv/user/wataame). SearchEncore is a community-run search service that complements the official bangumi.tv API.
121
+ - Thanks to [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) for the community-run Bangumi availability status service; the service author is also [`wataame`](https://bangumi.tv/user/wataame).
122
+ - This repository tries to reflect currently verifiable Bangumi behavior, but it does not promise full website feature coverage.
119
123
 
120
124
  ## License
121
125
 
package/README.md CHANGED
@@ -15,8 +15,8 @@
15
15
  npm / npx:
16
16
 
17
17
  ```bash
18
- npx @aronnax/bgm-cli --help
19
- npm install -g @aronnax/bgm-cli
18
+ npx @aronnaxlin/bgm-cli --help
19
+ npm install -g @aronnaxlin/bgm-cli
20
20
  ```
21
21
 
22
22
  macOS / Linux:
@@ -84,11 +84,14 @@ bgm collection indexes --limit 5
84
84
  bgm episode list 348335 --type main --limit 10
85
85
  bgm episode comments 348335 1
86
86
  bgm episode watch 348335 1
87
+ bgm book get 3510
88
+ bgm book ep 3510 10
87
89
  bgm blog --help
88
90
  bgm group list --sort members --limit 10
89
91
  bgm user friends --limit 5
90
92
  bgm group user --limit 5
91
93
  bgm index user --limit 5
94
+ bgm search subject "海贼王" --limit 5
92
95
  bgm trending subjects --type anime --limit 5
93
96
  bgm status --site bgm.tv
94
97
  bgm --json user me
@@ -119,8 +122,9 @@ bgm --json user me
119
122
  - 感谢 [`bgm.tv`](https://bgm.tv/) 提供 Bangumi 主站与社区生态。
120
123
  - 感谢 [`bangumi/server-private`](https://github.com/bangumi/server-private) 提供 private API 相关实现参考。
121
124
  - 感谢 [`bangumi/api`](https://github.com/bangumi/api) 提供公开 API 相关实现与文档基础。
122
- - 感谢 [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) 提供社区维护的 Bangumi 可用性状态观测能力;该服务作者为 [`wataame`](https://bangumi.tv/user/wataame)。
123
- - 本仓库会尽量反映当前可验证的 Bangumi 行为约束,但不承诺覆盖网站上的全部功能,也不承诺第三方站点行为长期稳定不变。
125
+ - 感谢 [`SearchEncore`](https://bgmdb.ry.mk/v1/docs)(`bgmdb.ry.mk`)提供社区维护的 Bangumi 增强搜索能力;该服务作者为 [`wataame`](https://bangumi.tv/user/wataame)。SearchEncore 是社区成员自发维护的搜索服务,数据来自社区聚合,与 bangumi.tv 官方接口互补。
126
+ - 感谢 [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) 提供社区维护的 Bangumi 可用性状态观测能力;该服务作者同样为 [`wataame`](https://bangumi.tv/user/wataame)。
127
+ - 本仓库会尽量反映当前可验证的 Bangumi 行为约束,但不承诺覆盖网站上的全部功能。
124
128
 
125
129
  ## 许可证
126
130
 
package/README.zh-TW.md CHANGED
@@ -15,8 +15,8 @@
15
15
  npm / npx:
16
16
 
17
17
  ```bash
18
- npx @aronnax/bgm-cli --help
19
- npm install -g @aronnax/bgm-cli
18
+ npx @aronnaxlin/bgm-cli --help
19
+ npm install -g @aronnaxlin/bgm-cli
20
20
  ```
21
21
 
22
22
  macOS / Linux:
@@ -80,9 +80,12 @@ bgm character search "明日香" --limit 3
80
80
  bgm person search "庵野" --limit 3
81
81
  bgm collection get 348335
82
82
  bgm collection indexes --user sai --limit 5
83
+ bgm book get 3510
84
+ bgm book ep 3510 10
83
85
  bgm group list --sort members --limit 10
84
86
  bgm group user sai --limit 5
85
87
  bgm index user sai --limit 5
88
+ bgm search subject "海賊王" --limit 5
86
89
  bgm trending subjects --type anime --limit 5
87
90
  bgm --json user me
88
91
  ```
@@ -114,8 +117,9 @@ bgm --json user me
114
117
  - 感謝 [`bgm.tv`](https://bgm.tv/) 提供 Bangumi 主站與社群生態。
115
118
  - 感謝 [`bangumi/server-private`](https://github.com/bangumi/server-private) 提供 private API 相關實作參考。
116
119
  - 感謝 [`bangumi/api`](https://github.com/bangumi/api) 提供公開 API 相關實作與文件基礎。
117
- - 感謝 [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) 提供社群維護的 Bangumi 可用性狀態觀測能力;該服務作者為 [`wataame`](https://bangumi.tv/user/wataame)。
118
- - 本倉庫會盡量反映目前可驗證的 Bangumi 行為限制,但不承諾覆蓋網站上的全部功能,也不承諾第三方站點行為會長期穩定不變。
120
+ - 感謝 [`SearchEncore`](https://bgmdb.ry.mk/v1/docs)(`bgmdb.ry.mk`)提供社群維護的 Bangumi 增強搜尋能力;該服務作者為 [`wataame`](https://bangumi.tv/user/wataame)。SearchEncore 是社群成員自發維護的搜尋服務,資料來自社群聚合,與 bangumi.tv 官方介面互補。
121
+ - 感謝 [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) 提供社群維護的 Bangumi 可用性狀態觀測能力;該服務作者同樣為 [`wataame`](https://bangumi.tv/user/wataame)。
122
+ - 本倉庫會盡量反映目前可驗證的 Bangumi 行為限制,但不承諾覆蓋網站上的全部功能。
119
123
 
120
124
  ## 授權
121
125
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aronnaxlin/bgm-cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.2",
4
4
  "description": "Command-line client for Bangumi.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "aronnaxlin",
package/src/cli.js CHANGED
@@ -13,6 +13,7 @@ import { BangumiClient, BangumiOAuthClient } from "./core/client.js";
13
13
  import { getInstalledProxy, installProxyFromConfig, resolveProxyUrl } from "./core/proxy.js";
14
14
  import { DEFAULT_TURNSTILE_TIMEOUT_MS, startTurnstileFlow } from "./core/turnstile.js";
15
15
  import {
16
+ AUTH_CONFIG_KEYS,
16
17
  ConfigError,
17
18
  clearConfigValue,
18
19
  clearConfigValues,
@@ -20,8 +21,12 @@ import {
20
21
  getConfig,
21
22
  getConfigFilePath,
22
23
  getConfigSourceFilePath,
24
+ getProfileOverride,
23
25
  normalizeConfigValue,
26
+ readConfig,
27
+ replaceConfigValues,
24
28
  setConfigValues,
29
+ setProfileOverride,
25
30
  } from "./core/config.js";
26
31
  import { CommandError, formatDisplayResult, printResult, printUsage } from "./core/output.js";
27
32
  import {
@@ -66,6 +71,13 @@ import {
66
71
  fallbackUserAgent,
67
72
  getPrivateLoginUrl,
68
73
  } from "./utils/auth.js";
74
+ import {
75
+ buildProfileListPayload,
76
+ computeProfileDelete,
77
+ computeProfileSave,
78
+ computeProfileSwitch,
79
+ listAuthEnvOverrides,
80
+ } from "./utils/profiles.js";
69
81
  import {
70
82
  getManagedInstallDir,
71
83
  getShellReloadHint,
@@ -106,21 +118,15 @@ import { runCharacterCommand } from "./commands/character.js";
106
118
  import { runPersonCommand } from "./commands/person.js";
107
119
  import { runTrendingCommand } from "./commands/trending.js";
108
120
  import { runNotifyCommand } from "./commands/notify.js";
121
+ import { runBookCommand } from "./commands/book.js";
122
+ import { runSearchCommand } from "./commands/search.js";
123
+ import { runUrlCommand } from "./commands/url.js";
124
+ import { looksLikeBangumiUrl } from "./utils/bangumi-url.js";
109
125
 
110
126
  const CLI_DIR = path.dirname(fileURLToPath(import.meta.url));
111
127
  const REPO_ROOT = path.resolve(CLI_DIR, "..");
112
128
 
113
129
  const REMOTE_INSTALL_SCRIPT_BASE_URL = "https://raw.githubusercontent.com/aronnaxlin/bgm-cli/main/scripts";
114
- const AUTH_CONFIG_KEYS = [
115
- "accessToken",
116
- "refreshToken",
117
- "tokenType",
118
- "privateSessionId",
119
- "privateSessionUpdatedAt",
120
- "clientId",
121
- "clientSecret",
122
- "redirectUri",
123
- ];
124
130
 
125
131
  async function main(argv) {
126
132
  const parsed = parseGlobalArgs(argv);
@@ -140,25 +146,43 @@ async function main(argv) {
140
146
  return;
141
147
  }
142
148
 
149
+ if (hasHelpFlag(parsed.args)) {
150
+ printUsage(resolveHelpTarget(parsed.args));
151
+ return;
152
+ }
153
+
154
+ if (parsed.profile !== undefined) {
155
+ setProfileOverride(parsed.profile);
156
+ getConfig();
157
+ warnAuthEnvOverrides();
158
+ }
159
+
143
160
  if (parsed.init) {
161
+ ensureNoProfileOverride("bgm --init");
144
162
  await runInitWizard(context);
145
163
  return;
146
164
  }
147
165
 
148
- if (parsed.args.length === 0) {
149
- printUsage();
166
+ if (parsed.url !== undefined) {
167
+ await runUrlCommand([parsed.url, ...parsed.args], context);
150
168
  return;
151
169
  }
152
170
 
153
- if (hasHelpFlag(parsed.args)) {
154
- printUsage(resolveHelpTarget(parsed.args));
171
+ if (parsed.args.length === 0) {
172
+ printUsage();
155
173
  return;
156
174
  }
157
175
 
158
176
  const [group, command, ...rest] = parsed.args;
159
177
 
178
+ if (looksLikeBangumiUrl(group)) {
179
+ await runUrlCommand(parsed.args, context);
180
+ return;
181
+ }
182
+
160
183
  switch (group) {
161
184
  case "tui":
185
+ ensureNoProfileOverride("bgm tui");
162
186
  await runTui(context, { runConfigCommand, runSetupCommand });
163
187
  return;
164
188
  case "config":
@@ -204,18 +228,27 @@ async function main(argv) {
204
228
  case "collection":
205
229
  await runCollectionCommand(command, rest, context);
206
230
  return;
231
+ case "book":
232
+ await runBookCommand(command, rest, context);
233
+ return;
207
234
  case "status":
208
235
  await runStatusCommand(command, rest, context);
209
236
  return;
210
237
  case "user":
211
238
  await runUserCommand(command, rest, context);
212
239
  return;
240
+ case "search":
241
+ await runSearchCommand(command, rest, context);
242
+ return;
213
243
  case "notify":
214
244
  await runNotifyCommand(command, rest, context);
215
245
  return;
216
246
  case "calendar":
217
247
  await runCalendarCommand(command, rest, context);
218
248
  return;
249
+ case "url":
250
+ await runUrlCommand([command, ...rest], context);
251
+ return;
219
252
  default:
220
253
  throw new CommandError(`Unknown command group: ${group}`);
221
254
  }
@@ -406,6 +439,9 @@ async function runConfigCommand(command, args, context) {
406
439
  }
407
440
 
408
441
  const normalizedKey = normalizeConfigKey(key);
442
+ if (AUTH_CONFIG_KEYS.includes(normalizedKey)) {
443
+ ensureNoProfileOverride(`bgm config set ${normalizedKey}`);
444
+ }
409
445
  const normalizedValue = normalizeConfigValue(normalizedKey, value);
410
446
  await setConfigValues({ [normalizedKey]: normalizedValue });
411
447
  printResult(
@@ -425,6 +461,9 @@ async function runConfigCommand(command, args, context) {
425
461
  }
426
462
 
427
463
  const normalizedKey = normalizeConfigKey(key);
464
+ if (AUTH_CONFIG_KEYS.includes(normalizedKey)) {
465
+ ensureNoProfileOverride(`bgm config unset ${normalizedKey}`);
466
+ }
428
467
  await clearConfigValue(normalizedKey);
429
468
  printResult(
430
469
  {
@@ -513,6 +552,7 @@ async function runAuthCommand(command, args, context) {
513
552
 
514
553
  switch (command) {
515
554
  case "login": {
555
+ ensureNoProfileOverride("bgm auth login");
516
556
  const savedSessionId = getSavedPrivateSessionId(config);
517
557
  if (savedSessionId && !toBoolean(options.force, false)) {
518
558
  throw new CommandError("Private session is already saved. Run `bgm auth status` to inspect it, `bgm auth logout` to end it, or `bgm auth login --force` to replace it.");
@@ -554,6 +594,7 @@ async function runAuthCommand(command, args, context) {
554
594
  return;
555
595
  }
556
596
  case "logout": {
597
+ ensureNoProfileOverride("bgm auth logout");
557
598
  const sessionId = typeof config.privateSessionId === "string" ? config.privateSessionId.trim() : "";
558
599
  if (!sessionId) {
559
600
  throw new CommandError("No saved private API session. Run `bgm auth login` first, or use `bgm auth clear` to clear local auth state.");
@@ -594,6 +635,7 @@ async function runAuthCommand(command, args, context) {
594
635
  });
595
636
 
596
637
  if (toBoolean(options.save, false)) {
638
+ ensureNoProfileOverride("bgm auth token --save");
597
639
  await setConfigValues({
598
640
  clientId: options.clientId ?? config.clientId,
599
641
  clientSecret: options.clientSecret ?? config.clientSecret,
@@ -616,6 +658,7 @@ async function runAuthCommand(command, args, context) {
616
658
  });
617
659
 
618
660
  if (toBoolean(options.save, false)) {
661
+ ensureNoProfileOverride("bgm auth refresh --save");
619
662
  await setConfigValues({
620
663
  clientId: options.clientId ?? config.clientId,
621
664
  clientSecret: options.clientSecret ?? config.clientSecret,
@@ -662,11 +705,13 @@ async function runAuthCommand(command, args, context) {
662
705
  return;
663
706
  }
664
707
  case "session-login": {
708
+ ensureNoProfileOverride("bgm auth session-login");
665
709
  const result = await runPrivateSessionLogin(options, context);
666
710
  printResult(result, context);
667
711
  return;
668
712
  }
669
713
  case "set-token": {
714
+ ensureNoProfileOverride("bgm auth set-token");
670
715
  const accessToken = options.accessToken ?? firstPositional(options);
671
716
  if (!accessToken) {
672
717
  throw new CommandError("Usage: bgm auth set-token <access_token>");
@@ -688,6 +733,7 @@ async function runAuthCommand(command, args, context) {
688
733
  return;
689
734
  }
690
735
  case "set-session": {
736
+ ensureNoProfileOverride("bgm auth set-session");
691
737
  const rawSession = options.session ?? firstPositional(options);
692
738
  if (!rawSession) {
693
739
  throw new CommandError("Usage: bgm auth set-session <chiiNextSessionID|cookie_string>");
@@ -730,20 +776,135 @@ async function runAuthCommand(command, args, context) {
730
776
  return;
731
777
  }
732
778
  case "clear": {
779
+ ensureNoProfileOverride("bgm auth clear");
733
780
  const clearKeys = resolveAuthClearKeys(options);
734
- await clearConfigValues(clearKeys);
781
+ const rawConfig = await readConfig();
782
+ const isFullClear = AUTH_CONFIG_KEYS.every((key) => clearKeys.includes(key));
783
+ const keys = isFullClear && rawConfig.activeProfile !== undefined
784
+ ? [...clearKeys, "activeProfile"]
785
+ : clearKeys;
786
+ await clearConfigValues(keys);
735
787
  printResult(
736
788
  {
737
789
  resource: "auth-clear",
738
- cleared: clearKeys,
790
+ cleared: keys,
739
791
  configFile: getConfigFilePath(),
740
792
  },
741
793
  context,
742
794
  );
743
795
  return;
744
796
  }
797
+ case "profile": {
798
+ await runAuthProfileCommand(options, context);
799
+ return;
800
+ }
745
801
  default:
746
- throw new CommandError("Usage: bgm auth <login|logout|status|token-status|login-url|token|refresh|turnstile|session-login|set-token|set-session|session-status|clear> ...");
802
+ throw new CommandError("Usage: bgm auth <login|logout|status|token-status|login-url|token|refresh|turnstile|session-login|set-token|set-session|session-status|clear|profile> ...");
803
+ }
804
+ }
805
+
806
+ async function runAuthProfileCommand(options, context) {
807
+ const subcommand = getPositional(options, 0);
808
+ const name = getPositional(options, 1);
809
+
810
+ switch (subcommand) {
811
+ case "list": {
812
+ const rawConfig = await readConfig();
813
+ printResult(
814
+ buildProfileListPayload(rawConfig, {
815
+ configFile: getConfigFilePath(),
816
+ envOverrides: listAuthEnvOverrides(),
817
+ profileOverride: getProfileOverride(),
818
+ }),
819
+ context,
820
+ );
821
+ return;
822
+ }
823
+ case "save": {
824
+ ensureNoProfileOverride("bgm auth profile save");
825
+ if (!name) {
826
+ throw new CommandError("Usage: bgm auth profile save <name> [--force]");
827
+ }
828
+ const rawConfig = await readConfig();
829
+ const change = computeProfileSave(rawConfig, name, { force: toBoolean(options.force, false) });
830
+ await replaceConfigValues(change);
831
+ printResult(
832
+ {
833
+ resource: "auth-profile-mutation",
834
+ action: "save",
835
+ profile: change.profile,
836
+ activeProfile: change.profile,
837
+ configFile: getConfigFilePath(),
838
+ envOverrides: listAuthEnvOverrides(),
839
+ },
840
+ context,
841
+ );
842
+ return;
843
+ }
844
+ case "use": {
845
+ ensureNoProfileOverride("bgm auth profile use");
846
+ if (!name) {
847
+ throw new CommandError("Usage: bgm auth profile use <name> [--force]");
848
+ }
849
+ const rawConfig = await readConfig();
850
+ const change = computeProfileSwitch(rawConfig, name, { force: toBoolean(options.force, false) });
851
+ await replaceConfigValues(change);
852
+ printResult(
853
+ {
854
+ resource: "auth-profile-mutation",
855
+ action: "use",
856
+ profile: change.profile,
857
+ activeProfile: change.profile,
858
+ previousProfile: change.previousProfile,
859
+ syncedPrevious: change.syncedPrevious,
860
+ configFile: getConfigFilePath(),
861
+ envOverrides: listAuthEnvOverrides(),
862
+ },
863
+ context,
864
+ );
865
+ return;
866
+ }
867
+ case "delete": {
868
+ ensureNoProfileOverride("bgm auth profile delete");
869
+ if (!name) {
870
+ throw new CommandError("Usage: bgm auth profile delete <name>");
871
+ }
872
+ const rawConfig = await readConfig();
873
+ const change = computeProfileDelete(rawConfig, name);
874
+ await replaceConfigValues(change);
875
+ printResult(
876
+ {
877
+ resource: "auth-profile-mutation",
878
+ action: "delete",
879
+ profile: change.profile,
880
+ activeProfile: change.wasActive ? null : (typeof rawConfig.activeProfile === "string" ? rawConfig.activeProfile : null),
881
+ ...(change.wasActive ? { credentialsRetained: true } : {}),
882
+ configFile: getConfigFilePath(),
883
+ envOverrides: listAuthEnvOverrides(),
884
+ },
885
+ context,
886
+ );
887
+ return;
888
+ }
889
+ default:
890
+ throw new CommandError("Usage: bgm auth profile <list|save|use|delete> ...");
891
+ }
892
+ }
893
+
894
+ function warnAuthEnvOverrides() {
895
+ const envOverrides = listAuthEnvOverrides();
896
+ if (envOverrides.length > 0) {
897
+ process.stderr.write(
898
+ `Warning: environment variables override the --profile credentials: ${envOverrides.join(", ")}\n`,
899
+ );
900
+ }
901
+ }
902
+
903
+ function ensureNoProfileOverride(actionLabel) {
904
+ if (getProfileOverride()) {
905
+ throw new CommandError(
906
+ `--profile is a read-only account override; \`${actionLabel}\` would modify saved credentials. Run \`bgm auth profile use <name>\` to switch accounts instead.`,
907
+ );
747
908
  }
748
909
  }
749
910
 
@@ -779,10 +940,18 @@ function buildAuthStatusPayload(config) {
779
940
  const accessToken = typeof config.accessToken === "string" ? config.accessToken.trim() : "";
780
941
  const refreshToken = typeof config.refreshToken === "string" ? config.refreshToken.trim() : "";
781
942
  const privateSession = getSavedPrivateSessionId(config);
943
+ const activeProfile = typeof config.activeProfile === "string" && config.activeProfile.trim() !== ""
944
+ ? config.activeProfile.trim()
945
+ : null;
946
+ const profileOverride = getProfileOverride();
947
+ const envOverrides = profileOverride ? listAuthEnvOverrides() : [];
782
948
 
783
949
  return {
784
950
  resource: "auth-status",
785
951
  configFile: getConfigFilePath(),
952
+ ...(activeProfile ? { activeProfile } : {}),
953
+ ...(profileOverride ? { profileOverride } : {}),
954
+ ...(envOverrides.length > 0 ? { envOverrides } : {}),
786
955
  policy: "p1 requests use the private session cookie when saved; Access Token is not sent together with it.",
787
956
  channels: {
788
957
  accessToken: {
@@ -0,0 +1,156 @@
1
+ import { BangumiClient } from "../core/client.js";
2
+ import { getConfig } from "../core/config.js";
3
+ import { BangumiApiError } from "../core/http.js";
4
+ import { CommandError, printResult } from "../core/output.js";
5
+ import { firstPositional, getPositional, parseFlags } from "../utils/args.js";
6
+ import { normalizeNonNegativeInteger, normalizePositiveNumber } from "../utils/helpers.js";
7
+ import { SUBJECT_TYPE_MAP } from "../utils/validators.js";
8
+ import {
9
+ buildCollectionActionResult,
10
+ fetchMySubjectCollection,
11
+ fetchMySubjectCollectionVerified,
12
+ } from "../utils/collection-ops.js";
13
+
14
+ export async function runBookCommand(command, args, context) {
15
+ switch (command) {
16
+ case "get": {
17
+ const result = await executeBookGetCommand(args);
18
+ printResult(result, context);
19
+ return;
20
+ }
21
+ case "ep": {
22
+ const result = await executeBookEpCommand(args);
23
+ printResult(result, context);
24
+ return;
25
+ }
26
+ case "vol": {
27
+ const result = await executeBookVolCommand(args);
28
+ printResult(result, context);
29
+ return;
30
+ }
31
+ default:
32
+ throw new CommandError(
33
+ "Usage: bgm book <get|ep|vol> ...",
34
+ );
35
+ }
36
+ }
37
+
38
+ export async function executeBookGetCommand(args) {
39
+ const options = parseFlags(args);
40
+ const client = new BangumiClient(getConfig());
41
+ const subjectId = firstPositional(options);
42
+ if (!subjectId) {
43
+ throw new CommandError("Usage: bgm book get <subject_id>");
44
+ }
45
+
46
+ const subject = await client.getSubject(subjectId);
47
+ if (Number(subject?.type) !== SUBJECT_TYPE_MAP.book) {
48
+ throw new CommandError(
49
+ `Subject ${subjectId} is not a book-type entry (${subject?.name || "unknown"}). Use \`bgm episode list\` or \`bgm episode watch\` for anime/game/real entries.`,
50
+ );
51
+ }
52
+
53
+ let collection;
54
+ try {
55
+ collection = await fetchMySubjectCollection(client, subjectId);
56
+ } catch (error) {
57
+ if (error instanceof BangumiApiError && error.status === 404) {
58
+ throw new CommandError(
59
+ `Subject ${subjectId} (${subject?.name || "unknown"}) is not in your collection. Add it first with \`bgm collection collect ${subjectId} doing\`.`,
60
+ );
61
+ }
62
+ throw error;
63
+ }
64
+
65
+ return {
66
+ resource: "book-progress",
67
+ action: "get",
68
+ actionLabel: "Book reading progress",
69
+ subjectId: Number(subjectId),
70
+ subject,
71
+ collection,
72
+ };
73
+ }
74
+
75
+ export async function executeBookEpCommand(args) {
76
+ const options = parseFlags(args);
77
+ const client = new BangumiClient(getConfig());
78
+ const subjectId = firstPositional(options);
79
+ const chapterNumber = normalizePositiveNumber(getPositional(options, 1), "chapter number");
80
+ if (!subjectId || chapterNumber === undefined) {
81
+ throw new CommandError("Usage: bgm book ep <subject_id> <chapter_number>");
82
+ }
83
+
84
+ const subject = await client.getSubject(subjectId);
85
+ if (Number(subject?.type) !== SUBJECT_TYPE_MAP.book) {
86
+ throw new CommandError(
87
+ `Subject ${subjectId} is not a book-type entry (${subject?.name || "unknown"}). Use \`bgm episode watch\` for anime/game/real entries.`,
88
+ );
89
+ }
90
+
91
+ const collection = await ensureBookCollection(client, subjectId, subject);
92
+ await client.patchMyCollection(subjectId, { epStatus: chapterNumber });
93
+
94
+ const updatedCollection = await fetchMySubjectCollectionVerified(client, subjectId, {
95
+ expected: { ep_status: chapterNumber },
96
+ actionLabel: "Book chapter progress update",
97
+ mismatchMessage: (latest) =>
98
+ `Bangumi did not persist the requested chapter progress. Requested ep_status ${chapterNumber}, but read back ${latest?.ep_status ?? "-"}.`,
99
+ });
100
+
101
+ return buildCollectionActionResult({
102
+ action: "ep",
103
+ actionLabel: "Chapter progress updated",
104
+ subjectId,
105
+ subject,
106
+ collection: updatedCollection,
107
+ });
108
+ }
109
+
110
+ export async function executeBookVolCommand(args) {
111
+ const options = parseFlags(args);
112
+ const client = new BangumiClient(getConfig());
113
+ const subjectId = firstPositional(options);
114
+ const volumeNumber = normalizePositiveNumber(getPositional(options, 1), "volume number");
115
+ if (!subjectId || volumeNumber === undefined) {
116
+ throw new CommandError("Usage: bgm book vol <subject_id> <volume_number>");
117
+ }
118
+
119
+ const subject = await client.getSubject(subjectId);
120
+ if (Number(subject?.type) !== SUBJECT_TYPE_MAP.book) {
121
+ throw new CommandError(
122
+ `Subject ${subjectId} is not a book-type entry (${subject?.name || "unknown"}). Use \`bgm episode watch\` for anime/game/real entries.`,
123
+ );
124
+ }
125
+
126
+ const collection = await ensureBookCollection(client, subjectId, subject);
127
+ await client.patchMyCollection(subjectId, { volStatus: volumeNumber });
128
+
129
+ const updatedCollection = await fetchMySubjectCollectionVerified(client, subjectId, {
130
+ expected: { vol_status: volumeNumber },
131
+ actionLabel: "Book volume progress update",
132
+ mismatchMessage: (latest) =>
133
+ `Bangumi did not persist the requested volume progress. Requested vol_status ${volumeNumber}, but read back ${latest?.vol_status ?? "-"}.`,
134
+ });
135
+
136
+ return buildCollectionActionResult({
137
+ action: "vol",
138
+ actionLabel: "Volume progress updated",
139
+ subjectId,
140
+ subject,
141
+ collection: updatedCollection,
142
+ });
143
+ }
144
+
145
+ async function ensureBookCollection(client, subjectId, subject) {
146
+ try {
147
+ return await fetchMySubjectCollection(client, subjectId);
148
+ } catch (error) {
149
+ if (error instanceof BangumiApiError && error.status === 404) {
150
+ throw new CommandError(
151
+ `Subject ${subjectId} (${subject?.name || "unknown"}) is not in your collection. Add it first with \`bgm collection collect ${subjectId} doing\`, then retry.`,
152
+ );
153
+ }
154
+ throw error;
155
+ }
156
+ }
@@ -17,6 +17,7 @@ import {
17
17
  normalizeCollectionStatusValue,
18
18
  normalizeSortOrder,
19
19
  normalizeSubjectTypeFilter,
20
+ normalizeTagFilter,
20
21
  } from "../utils/validators.js";
21
22
  import { fetchAllCollections, sortCollections } from "../utils/collection.js";
22
23
  import {
@@ -103,6 +104,7 @@ export async function executeCollectionListCommand(args) {
103
104
  const order = normalizeSortOrder(options.order);
104
105
  const limit = parseOptionalInteger(options.limit);
105
106
  const offset = parseOptionalInteger(options.offset);
107
+ const tagFilter = normalizeTagFilter(options.tag);
106
108
 
107
109
  const apiQuery = {};
108
110
  if (subjectTypes.length === 1) {
@@ -125,6 +127,13 @@ export async function executeCollectionListCommand(args) {
125
127
  data = data.filter((item) => allowed.has(item.type));
126
128
  }
127
129
 
130
+ if (tagFilter.length > 0) {
131
+ data = data.filter((item) => {
132
+ const itemTags = item.interest?.tags ?? item.tags ?? [];
133
+ return tagFilter.every((tag) => itemTags.some((t) => String(t).toLowerCase() === tag.toLowerCase()));
134
+ });
135
+ }
136
+
128
137
  data = sortCollections(data, sort, order);
129
138
 
130
139
  const start = offset ?? 0;
@@ -141,6 +150,7 @@ export async function executeCollectionListCommand(args) {
141
150
  user: username,
142
151
  status: collectionTypes,
143
152
  subjectType: subjectTypes,
153
+ tag: tagFilter,
144
154
  sort,
145
155
  order,
146
156
  offset: offset ?? 0,