@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,450 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
6
+
7
+ export class ConfigError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = "ConfigError";
11
+ }
12
+ }
13
+
14
+ const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
15
+ const REPO_ROOT = path.resolve(MODULE_DIR, "../..");
16
+ const USER_CONFIG_DIR = resolveUserConfigDir();
17
+ const USER_CONFIG_FILE = path.join(USER_CONFIG_DIR, "config.json");
18
+ const PROJECT_CONFIG_DIR = path.join(REPO_ROOT, ".bgm-cli");
19
+ const PROJECT_CONFIG_FILE = path.join(PROJECT_CONFIG_DIR, "config.json");
20
+ const GLOBAL_INSTALL_MARKER = path.join(PROJECT_CONFIG_DIR, ".global-install-enabled");
21
+ const LEGACY_GLOBAL_INSTALL_MARKER = path.join(USER_CONFIG_DIR, ".global-install-enabled");
22
+ const DEV_ENV_FILE = path.join(REPO_ROOT, "bgm-dev.env");
23
+
24
+ const DEFAULT_CONFIG = {
25
+ appName: "bgm-cli",
26
+ appVersion: "1.0.0",
27
+ homepageLink: "https://github.com/aronnaxlin/bgm-cli",
28
+ developerId: "aronnaxlin",
29
+ oauthServerBaseUrl: "https://oauth-backend-jet.vercel.app",
30
+ timezone: "Asia/Shanghai",
31
+ };
32
+
33
+ const ENV_TO_KEY = {
34
+ BGM_ACCESS_TOKEN: "accessToken",
35
+ BGM_REFRESH_TOKEN: "refreshToken",
36
+ BGM_PRIVATE_SESSION_ID: "privateSessionId",
37
+ BGM_CLIENT_ID: "clientId",
38
+ BGM_CLIENT_SECRET: "clientSecret",
39
+ BGM_REDIRECT_URI: "redirectUri",
40
+ BGM_HOMEPAGE_LINK: "homepageLink",
41
+ BGM_OAUTH_SERVER_BASE_URL: "oauthServerBaseUrl",
42
+ BGM_DEVELOPER_ID: "developerId",
43
+ BGM_APP_NAME: "appName",
44
+ BGM_APP_VERSION: "appVersion",
45
+ BGM_USER_AGENT: "userAgent",
46
+ BGM_TIMEZONE: "timezone",
47
+ };
48
+
49
+ export function getConfigFilePath() {
50
+ return getActiveRuntimeConfigMeta().writeFile;
51
+ }
52
+
53
+ export function getConfigSourceFilePath() {
54
+ return getActiveRuntimeConfigMeta().sourceFile;
55
+ }
56
+
57
+ export function getConfig() {
58
+ const runtimeConfig = getActiveRuntimeConfigMeta().config;
59
+ const devConfig = readEnvConfigFileSafe(DEV_ENV_FILE);
60
+ const envConfig = {};
61
+
62
+ for (const [envName, key] of Object.entries(ENV_TO_KEY)) {
63
+ const value = process.env[envName];
64
+ if (value !== undefined && value !== "") {
65
+ envConfig[key] = normalizeEnvValue(key, value);
66
+ }
67
+ }
68
+
69
+ const merged = {
70
+ ...DEFAULT_CONFIG,
71
+ ...devConfig,
72
+ ...runtimeConfig,
73
+ ...envConfig,
74
+ };
75
+
76
+ return {
77
+ ...merged,
78
+ timezone: normalizeTimezone(merged.timezone),
79
+ userAgent: normalizeUserAgent(merged),
80
+ };
81
+ }
82
+
83
+ export function normalizeConfigValue(key, value) {
84
+ if (key === "timezone") {
85
+ return normalizeTimezone(value);
86
+ }
87
+
88
+ if (key === "proxy") {
89
+ return normalizeProxy(value);
90
+ }
91
+
92
+ return value;
93
+ }
94
+
95
+ export function normalizeProxy(value) {
96
+ if (value === undefined || value === null) {
97
+ return "";
98
+ }
99
+
100
+ const raw = String(value).trim();
101
+ if (raw === "") {
102
+ return "";
103
+ }
104
+
105
+ try {
106
+ const parsed = new URL(raw);
107
+ if (!["http:", "https:"].includes(parsed.protocol)) {
108
+ throw new ConfigError(`Unsupported proxy protocol: ${parsed.protocol}`);
109
+ }
110
+ return parsed.toString().replace(/\/+$/, "");
111
+ } catch (error) {
112
+ if (error instanceof ConfigError) {
113
+ throw error;
114
+ }
115
+ throw new ConfigError(`Invalid proxy URL: ${value}`);
116
+ }
117
+ }
118
+
119
+ export function normalizeTimezone(value) {
120
+ if (value === undefined || value === null || value === "") {
121
+ return DEFAULT_CONFIG.timezone;
122
+ }
123
+
124
+ const raw = String(value).trim();
125
+ const aliasMap = {
126
+ cst: "Asia/Shanghai",
127
+ "utc+8": "Asia/Shanghai",
128
+ "utc+08:00": "Asia/Shanghai",
129
+ "gmt+8": "Asia/Shanghai",
130
+ "gmt+08:00": "Asia/Shanghai",
131
+ beijing: "Asia/Shanghai",
132
+ shanghai: "Asia/Shanghai",
133
+ "asia/shanghai": "Asia/Shanghai",
134
+ };
135
+ const normalized = aliasMap[raw.toLowerCase()] ?? raw;
136
+
137
+ try {
138
+ new Intl.DateTimeFormat("en-US", { timeZone: normalized }).format(new Date());
139
+ return normalized;
140
+ } catch {
141
+ throw new ConfigError(`Unsupported timezone: ${value}`);
142
+ }
143
+ }
144
+
145
+ export async function setConfigValues(partial) {
146
+ const runtimeMeta = getActiveRuntimeConfigMeta();
147
+ const configFile = runtimeMeta.writeFile;
148
+ const configDir = path.dirname(configFile);
149
+ const current = runtimeMeta.config;
150
+ const next = {
151
+ ...current,
152
+ ...partial,
153
+ };
154
+
155
+ await mkdir(configDir, { recursive: true });
156
+ await writeFile(configFile, `${JSON.stringify(next, null, 2)}\n`, "utf8");
157
+ }
158
+
159
+ export async function clearConfigValue(key) {
160
+ const runtimeMeta = getActiveRuntimeConfigMeta();
161
+ const configFile = runtimeMeta.writeFile;
162
+ const configDir = path.dirname(configFile);
163
+ const current = { ...runtimeMeta.config };
164
+ delete current[key];
165
+
166
+ await mkdir(configDir, { recursive: true });
167
+ await writeFile(configFile, `${JSON.stringify(current, null, 2)}\n`, "utf8");
168
+ }
169
+
170
+ export async function clearConfigValues(keys) {
171
+ const runtimeMeta = getActiveRuntimeConfigMeta();
172
+ const configFile = runtimeMeta.writeFile;
173
+ const configDir = path.dirname(configFile);
174
+ const current = { ...runtimeMeta.config };
175
+
176
+ for (const key of keys) {
177
+ delete current[key];
178
+ }
179
+
180
+ await mkdir(configDir, { recursive: true });
181
+ await writeFile(configFile, `${JSON.stringify(current, null, 2)}\n`, "utf8");
182
+ }
183
+
184
+ export async function readConfig() {
185
+ return getActiveRuntimeConfigMeta().config;
186
+ }
187
+
188
+ export async function enableGlobalConfigMode() {
189
+ await mkdir(PROJECT_CONFIG_DIR, { recursive: true });
190
+ await writeFile(GLOBAL_INSTALL_MARKER, "enabled\n", "utf8");
191
+
192
+ const userState = readJsonFileState(USER_CONFIG_FILE);
193
+ if (userState.exists) {
194
+ if (!userState.ok) {
195
+ throw new ConfigError(`Failed to parse global config file: ${USER_CONFIG_FILE}`);
196
+ }
197
+ return {
198
+ markerFile: GLOBAL_INSTALL_MARKER,
199
+ configFile: USER_CONFIG_FILE,
200
+ migrated: false,
201
+ };
202
+ }
203
+
204
+ const projectState = readJsonFileState(PROJECT_CONFIG_FILE);
205
+ if (projectState.exists) {
206
+ if (!projectState.ok) {
207
+ throw new ConfigError(`Failed to parse project config file: ${PROJECT_CONFIG_FILE}`);
208
+ }
209
+
210
+ await mkdir(USER_CONFIG_DIR, { recursive: true });
211
+ await writeFile(USER_CONFIG_FILE, `${JSON.stringify(projectState.value, null, 2)}\n`, "utf8");
212
+ return {
213
+ markerFile: GLOBAL_INSTALL_MARKER,
214
+ configFile: USER_CONFIG_FILE,
215
+ migrated: true,
216
+ };
217
+ }
218
+
219
+ return {
220
+ markerFile: GLOBAL_INSTALL_MARKER,
221
+ configFile: USER_CONFIG_FILE,
222
+ migrated: false,
223
+ };
224
+ }
225
+
226
+ function getActiveRuntimeConfigMeta() {
227
+ if (isGlobalInstallEnabled() || isPackageInstall()) {
228
+ return getGlobalRuntimeConfigMeta();
229
+ }
230
+ return getProjectRuntimeConfigMeta();
231
+ }
232
+
233
+ function getGlobalRuntimeConfigMeta() {
234
+ const userState = readJsonFileState(USER_CONFIG_FILE);
235
+ if (userState.exists) {
236
+ if (!userState.ok) {
237
+ throw new ConfigError(`Failed to parse global config file: ${USER_CONFIG_FILE}`);
238
+ }
239
+ return {
240
+ config: userState.value,
241
+ sourceFile: USER_CONFIG_FILE,
242
+ writeFile: USER_CONFIG_FILE,
243
+ };
244
+ }
245
+
246
+ const projectState = readJsonFileState(PROJECT_CONFIG_FILE);
247
+ if (projectState.exists) {
248
+ if (!projectState.ok) {
249
+ throw new ConfigError(`Failed to parse project config file: ${PROJECT_CONFIG_FILE}`);
250
+ }
251
+ return {
252
+ config: projectState.value,
253
+ sourceFile: PROJECT_CONFIG_FILE,
254
+ writeFile: USER_CONFIG_FILE,
255
+ };
256
+ }
257
+
258
+ return {
259
+ config: {},
260
+ sourceFile: USER_CONFIG_FILE,
261
+ writeFile: USER_CONFIG_FILE,
262
+ };
263
+ }
264
+
265
+ function getProjectRuntimeConfigMeta() {
266
+ const projectState = readJsonFileState(PROJECT_CONFIG_FILE);
267
+ if (projectState.exists) {
268
+ if (!projectState.ok) {
269
+ throw new ConfigError(`Failed to parse project config file: ${PROJECT_CONFIG_FILE}`);
270
+ }
271
+ return {
272
+ config: projectState.value,
273
+ sourceFile: PROJECT_CONFIG_FILE,
274
+ writeFile: PROJECT_CONFIG_FILE,
275
+ };
276
+ }
277
+
278
+ return {
279
+ config: {},
280
+ sourceFile: PROJECT_CONFIG_FILE,
281
+ writeFile: PROJECT_CONFIG_FILE,
282
+ };
283
+ }
284
+
285
+ function isGlobalInstallEnabled() {
286
+ return existsSync(GLOBAL_INSTALL_MARKER) || existsSync(LEGACY_GLOBAL_INSTALL_MARKER);
287
+ }
288
+
289
+ function isPackageInstall() {
290
+ return REPO_ROOT.split(path.sep).includes("node_modules");
291
+ }
292
+
293
+ function resolveUserConfigDir() {
294
+ if (process.platform === "win32" && process.env.APPDATA) {
295
+ return path.join(process.env.APPDATA, "bgm-cli");
296
+ }
297
+
298
+ return path.join(os.homedir(), ".config", "bgm-cli");
299
+ }
300
+
301
+ function readJsonFileState(filePath) {
302
+ if (!existsSync(filePath)) {
303
+ return {
304
+ exists: false,
305
+ ok: true,
306
+ value: {},
307
+ };
308
+ }
309
+
310
+ try {
311
+ const content = readFileSync(filePath, "utf8");
312
+ return {
313
+ exists: true,
314
+ ok: true,
315
+ value: JSON.parse(content),
316
+ };
317
+ } catch {
318
+ return {
319
+ exists: true,
320
+ ok: false,
321
+ value: {},
322
+ };
323
+ }
324
+ }
325
+
326
+ function readEnvConfigFileSafe(filePath) {
327
+ try {
328
+ const content = readFileSync(filePath, "utf8");
329
+ return parseEnvConfig(content);
330
+ } catch {
331
+ return {};
332
+ }
333
+ }
334
+
335
+ function parseEnvConfig(content) {
336
+ const config = {};
337
+ const lines = String(content).split(/\r?\n/);
338
+
339
+ for (const line of lines) {
340
+ const trimmed = line.trim();
341
+ if (!trimmed || trimmed.startsWith("#")) {
342
+ continue;
343
+ }
344
+
345
+ const separatorIndex = trimmed.indexOf("=");
346
+ if (separatorIndex === -1) {
347
+ continue;
348
+ }
349
+
350
+ const rawKey = trimmed.slice(0, separatorIndex).trim();
351
+ const rawValue = trimmed.slice(separatorIndex + 1).trim();
352
+ const value = stripQuotedValue(rawValue);
353
+
354
+ if (!value) {
355
+ continue;
356
+ }
357
+
358
+ const key = ENV_TO_KEY[rawKey];
359
+ if (key) {
360
+ config[key] = normalizeEnvValue(key, value);
361
+ }
362
+ }
363
+
364
+ return config;
365
+ }
366
+
367
+ function normalizeEnvValue(key, value) {
368
+ if (key === "oauthServerBaseUrl") {
369
+ return String(value).replace(/\/+$/, "");
370
+ }
371
+
372
+ if (key === "accessToken") {
373
+ return String(value);
374
+ }
375
+
376
+ if (key === "timezone") {
377
+ return normalizeTimezone(value);
378
+ }
379
+
380
+ if (key === "proxy") {
381
+ return normalizeProxy(value);
382
+ }
383
+
384
+ return value;
385
+ }
386
+
387
+ function normalizeUserAgent(config) {
388
+ const current = config.userAgent;
389
+ const recommended = buildRecommendedUserAgent(config);
390
+ const legacyRecommended = buildRecommendedUserAgent({
391
+ ...config,
392
+ appVersion: "0.1.0",
393
+ });
394
+
395
+ if (!current) {
396
+ return recommended;
397
+ }
398
+
399
+ const appName = config.appName ?? "bgm-cli";
400
+ const version = config.appVersion ?? "1.0.0";
401
+ const genericValues = new Set([
402
+ `${appName}/${version}`,
403
+ `${appName}/0.1.0`,
404
+ "bgm-cli/0.1.3",
405
+ "bgm-cli/0.1.0",
406
+ "yourname/bgm-cli/0.1.3",
407
+ "yourname/bgm-cli/0.1.0",
408
+ ]);
409
+
410
+ if ((genericValues.has(current) || current === legacyRecommended) && recommended) {
411
+ return recommended;
412
+ }
413
+
414
+ return current;
415
+ }
416
+
417
+ function buildRecommendedUserAgent(config) {
418
+ const developerId = config.developerId ?? extractGithubUsername(config.homepageLink);
419
+ const appName = config.appName ?? "bgm-cli";
420
+ const version = config.appVersion ?? "1.0.0";
421
+ const homepageLink = config.homepageLink;
422
+
423
+ let userAgent = developerId ? `${developerId}/${appName}/${version}` : `${appName}/${version}`;
424
+
425
+ if (homepageLink) {
426
+ userAgent += ` (${homepageLink})`;
427
+ }
428
+
429
+ return userAgent;
430
+ }
431
+
432
+ function extractGithubUsername(homepageLink) {
433
+ if (!homepageLink) {
434
+ return null;
435
+ }
436
+
437
+ const githubMatch = String(homepageLink).match(/^https?:\/\/github\.com\/([^/]+)/i);
438
+ return githubMatch?.[1] ?? null;
439
+ }
440
+
441
+ function stripQuotedValue(value) {
442
+ const trimmed = String(value).trim();
443
+ if (
444
+ (trimmed.startsWith('"') && trimmed.endsWith('"')) ||
445
+ (trimmed.startsWith("'") && trimmed.endsWith("'"))
446
+ ) {
447
+ return trimmed.slice(1, -1);
448
+ }
449
+ return trimmed;
450
+ }
@@ -0,0 +1,144 @@
1
+ export class BangumiApiError extends Error {
2
+ constructor(message, { status, details } = {}) {
3
+ super(message);
4
+ this.name = "BangumiApiError";
5
+ this.status = status;
6
+ this.details = details;
7
+ }
8
+ }
9
+
10
+ export async function requestJson(url, options = {}) {
11
+ const { payload } = await requestJsonWithMeta(url, options);
12
+ return payload;
13
+ }
14
+
15
+ export async function requestJsonWithMeta(url, options = {}) {
16
+ const { response } = await performRequest(url, options);
17
+
18
+ const contentType = response.headers.get("content-type") ?? "";
19
+ const isJson = contentType.includes("application/json");
20
+ const payload = isJson ? await response.json() : await response.text();
21
+
22
+ if (!response.ok) {
23
+ throw new BangumiApiError(extractErrorMessage(payload, response.statusText), {
24
+ status: response.status,
25
+ details: payload,
26
+ });
27
+ }
28
+
29
+ return {
30
+ payload,
31
+ response,
32
+ };
33
+ }
34
+
35
+ export async function requestText(url, options = {}) {
36
+ const { response } = await performRequest(url, options);
37
+ const payload = await response.text();
38
+
39
+ if (!response.ok) {
40
+ throw new BangumiApiError(extractErrorMessage(payload, response.statusText), {
41
+ status: response.status,
42
+ details: payload,
43
+ });
44
+ }
45
+
46
+ return payload;
47
+ }
48
+
49
+ async function performRequest(url, options = {}) {
50
+ const targetUrl = new URL(url);
51
+
52
+ for (const [key, value] of Object.entries(options.query ?? {})) {
53
+ if (value === undefined || value === null || value === "") {
54
+ continue;
55
+ }
56
+ if (Array.isArray(value)) {
57
+ for (const v of value) {
58
+ if (v !== undefined && v !== null && v !== "") {
59
+ targetUrl.searchParams.append(key, String(v));
60
+ }
61
+ }
62
+ } else {
63
+ targetUrl.searchParams.set(key, String(value));
64
+ }
65
+ }
66
+
67
+ const requestBody = buildRequestBody(options);
68
+
69
+ let response;
70
+ try {
71
+ response = await fetch(targetUrl, {
72
+ method: options.method ?? "GET",
73
+ headers: options.headers,
74
+ body: requestBody,
75
+ });
76
+ } catch (error) {
77
+ throw new BangumiApiError(`Network request failed: ${error?.cause?.code ?? error?.message ?? "unknown error"}`, {
78
+ details: {
79
+ url: targetUrl.toString(),
80
+ method: options.method ?? "GET",
81
+ },
82
+ });
83
+ }
84
+
85
+ return {
86
+ targetUrl,
87
+ response,
88
+ };
89
+ }
90
+
91
+ function buildRequestBody(options) {
92
+ if (options.form !== undefined) {
93
+ return new URLSearchParams(cleanObject(options.form)).toString();
94
+ }
95
+
96
+ if (options.body !== undefined) {
97
+ return JSON.stringify(cleanObject(options.body));
98
+ }
99
+
100
+ return undefined;
101
+ }
102
+
103
+ function cleanObject(input) {
104
+ if (input === null || input === undefined) {
105
+ return input;
106
+ }
107
+
108
+ if (Array.isArray(input)) {
109
+ return input.map(cleanObject);
110
+ }
111
+
112
+ if (typeof input !== "object") {
113
+ return input;
114
+ }
115
+
116
+ return Object.fromEntries(
117
+ Object.entries(input)
118
+ .filter(([, value]) => value !== undefined)
119
+ .map(([key, value]) => [key, cleanObject(value)]),
120
+ );
121
+ }
122
+
123
+ function extractErrorMessage(payload, fallback) {
124
+ if (typeof payload === "string" && payload.trim() !== "") {
125
+ return payload;
126
+ }
127
+
128
+ if (payload && typeof payload === "object") {
129
+ if (typeof payload.description === "string") {
130
+ return payload.description;
131
+ }
132
+ if (typeof payload.error === "string") {
133
+ return payload.error;
134
+ }
135
+ if (typeof payload.title === "string") {
136
+ return payload.title;
137
+ }
138
+ if (Array.isArray(payload) && payload.length > 0) {
139
+ return payload[0]?.msg ?? fallback;
140
+ }
141
+ }
142
+
143
+ return fallback || "Request failed";
144
+ }