@aronnaxlin/bgm-cli 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,203 @@
1
+ import process from "node:process";
2
+ import { AUTH_CONFIG_KEYS } from "../core/config.js";
3
+ import { CommandError } from "../core/output.js";
4
+ import { hasSavedConfigValue, previewToken } from "./helpers.js";
5
+
6
+ export const PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/;
7
+
8
+ const AUTH_ENV_OVERRIDE_NAMES = [
9
+ "BGM_ACCESS_TOKEN",
10
+ "BGM_REFRESH_TOKEN",
11
+ "BGM_PRIVATE_SESSION_ID",
12
+ "BGM_CLIENT_ID",
13
+ "BGM_CLIENT_SECRET",
14
+ "BGM_REDIRECT_URI",
15
+ ];
16
+
17
+ export function validateProfileName(name) {
18
+ const value = typeof name === "string" ? name.trim() : "";
19
+ if (!PROFILE_NAME_PATTERN.test(value)) {
20
+ throw new CommandError(
21
+ `Invalid profile name: ${String(name ?? "")}. Names must match [A-Za-z0-9][A-Za-z0-9._-]{0,31}.`,
22
+ );
23
+ }
24
+ return value;
25
+ }
26
+
27
+ export function pickAuthSnapshot(source) {
28
+ const snapshot = {};
29
+ if (!isPlainObject(source)) {
30
+ return snapshot;
31
+ }
32
+ for (const key of AUTH_CONFIG_KEYS) {
33
+ if (source[key] !== undefined) {
34
+ snapshot[key] = source[key];
35
+ }
36
+ }
37
+ return snapshot;
38
+ }
39
+
40
+ export function snapshotHasCredentials(snapshot) {
41
+ return hasSavedConfigValue(snapshot?.accessToken) || hasSavedConfigValue(snapshot?.privateSessionId);
42
+ }
43
+
44
+ export function computeProfileSave(rawConfig, name, { force = false } = {}) {
45
+ const profileName = validateProfileName(name);
46
+ const profiles = readProfilesMap(rawConfig);
47
+ const snapshot = pickAuthSnapshot(rawConfig);
48
+ if (!snapshotHasCredentials(snapshot)) {
49
+ throw new CommandError(
50
+ "No saved auth credentials to snapshot. Run `bgm auth login` or `bgm auth set-token` first.",
51
+ );
52
+ }
53
+ const activeProfile = readActiveProfile(rawConfig);
54
+ if (hasProfile(profiles, profileName) && profileName !== activeProfile && !force) {
55
+ throw new CommandError(`Profile already exists: ${profileName}. Pass --force to overwrite it.`);
56
+ }
57
+ return {
58
+ set: {
59
+ profiles: { ...profiles, [profileName]: snapshot },
60
+ activeProfile: profileName,
61
+ },
62
+ remove: [],
63
+ profile: profileName,
64
+ };
65
+ }
66
+
67
+ export function computeProfileSwitch(rawConfig, name, { force = false } = {}) {
68
+ const profileName = validateProfileName(name);
69
+ const profiles = readProfilesMap(rawConfig);
70
+ if (!hasProfile(profiles, profileName)) {
71
+ throw profileNotFoundError(profileName, profiles);
72
+ }
73
+ if (!snapshotHasCredentials(pickAuthSnapshot(profiles[profileName]))) {
74
+ throw new CommandError(
75
+ `Profile has no saved credentials: ${profileName}. Switching to it would leave you signed out; run \`bgm auth profile delete ${profileName}\` and save it again.`,
76
+ );
77
+ }
78
+ const activeProfile = readActiveProfile(rawConfig);
79
+ const currentSnapshot = pickAuthSnapshot(rawConfig);
80
+ const syncedPrevious = Boolean(activeProfile) && snapshotHasCredentials(currentSnapshot);
81
+ if (!syncedPrevious && snapshotHasCredentials(currentSnapshot) && !force
82
+ && !isSnapshotSavedIn(profiles, currentSnapshot)) {
83
+ throw new CommandError(
84
+ "The current credentials are not stored in any profile, and no active profile is set to sync them back into; switching would discard them. Run `bgm auth profile save <name>` first, or pass --force to discard them.",
85
+ );
86
+ }
87
+ const nextProfiles = { ...profiles };
88
+ if (syncedPrevious) {
89
+ nextProfiles[activeProfile] = currentSnapshot;
90
+ }
91
+ const targetSnapshot = pickAuthSnapshot(nextProfiles[profileName]);
92
+ const remove = AUTH_CONFIG_KEYS.filter((key) => targetSnapshot[key] === undefined);
93
+ return {
94
+ set: {
95
+ ...targetSnapshot,
96
+ profiles: nextProfiles,
97
+ activeProfile: profileName,
98
+ },
99
+ remove,
100
+ profile: profileName,
101
+ previousProfile: activeProfile || null,
102
+ syncedPrevious,
103
+ };
104
+ }
105
+
106
+ export function computeProfileDelete(rawConfig, name) {
107
+ const profileName = validateProfileName(name);
108
+ const profiles = readProfilesMap(rawConfig);
109
+ if (!hasProfile(profiles, profileName)) {
110
+ throw profileNotFoundError(profileName, profiles);
111
+ }
112
+ const nextProfiles = { ...profiles };
113
+ delete nextProfiles[profileName];
114
+ const wasActive = readActiveProfile(rawConfig) === profileName;
115
+ return {
116
+ set: { profiles: nextProfiles },
117
+ remove: wasActive ? ["activeProfile"] : [],
118
+ profile: profileName,
119
+ wasActive,
120
+ };
121
+ }
122
+
123
+ export function buildProfileListPayload(rawConfig, { configFile, envOverrides = [], profileOverride = null } = {}) {
124
+ const profilesMap = readProfilesMap(rawConfig);
125
+ const activeProfile = readActiveProfile(rawConfig) || null;
126
+ const profiles = Object.keys(profilesMap).sort().map((name) => {
127
+ const snapshot = pickAuthSnapshot(profilesMap[name]);
128
+ const accessTokenSaved = hasSavedConfigValue(snapshot.accessToken);
129
+ const privateSessionSaved = hasSavedConfigValue(snapshot.privateSessionId);
130
+ return {
131
+ name,
132
+ active: name === activeProfile,
133
+ accessTokenSaved,
134
+ accessTokenPreview: accessTokenSaved ? previewToken(snapshot.accessToken) : null,
135
+ refreshTokenSaved: hasSavedConfigValue(snapshot.refreshToken),
136
+ privateSessionSaved,
137
+ privateSessionPreview: privateSessionSaved ? previewToken(snapshot.privateSessionId) : null,
138
+ privateSessionUpdatedAt: snapshot.privateSessionUpdatedAt ?? null,
139
+ };
140
+ });
141
+ return {
142
+ resource: "auth-profile-list",
143
+ configFile: configFile ?? null,
144
+ activeProfile,
145
+ activeProfileMissing: Boolean(activeProfile && !hasProfile(profilesMap, activeProfile)),
146
+ ...(profileOverride ? { profileOverride } : {}),
147
+ envOverrides,
148
+ profiles,
149
+ };
150
+ }
151
+
152
+ export function listAuthEnvOverrides(env = process.env) {
153
+ return AUTH_ENV_OVERRIDE_NAMES.filter((envName) => {
154
+ const value = env[envName];
155
+ return typeof value === "string" && value.trim() !== "";
156
+ });
157
+ }
158
+
159
+ function readProfilesMap(rawConfig) {
160
+ const profiles = rawConfig?.profiles;
161
+ if (!isPlainObject(profiles)) {
162
+ return {};
163
+ }
164
+ const result = {};
165
+ for (const [name, snapshot] of Object.entries(profiles)) {
166
+ if (isPlainObject(snapshot)) {
167
+ result[name] = snapshot;
168
+ }
169
+ }
170
+ return result;
171
+ }
172
+
173
+ function hasProfile(profiles, name) {
174
+ return Object.hasOwn(profiles, name);
175
+ }
176
+
177
+ function isSnapshotSavedIn(profiles, snapshot) {
178
+ return Object.values(profiles).some((saved) => sameCredentials(pickAuthSnapshot(saved), snapshot));
179
+ }
180
+
181
+ function sameCredentials(left, right) {
182
+ return credentialValue(left.accessToken) === credentialValue(right.accessToken)
183
+ && credentialValue(left.privateSessionId) === credentialValue(right.privateSessionId);
184
+ }
185
+
186
+ function credentialValue(value) {
187
+ return typeof value === "string" ? value.trim() : "";
188
+ }
189
+
190
+ function readActiveProfile(rawConfig) {
191
+ return typeof rawConfig?.activeProfile === "string" ? rawConfig.activeProfile.trim() : "";
192
+ }
193
+
194
+ function profileNotFoundError(name, profilesMap) {
195
+ const names = Object.keys(profilesMap).sort();
196
+ return new CommandError(
197
+ `Profile not found: ${name}. Saved profiles: ${names.length > 0 ? names.join(", ") : "(none)"}`,
198
+ );
199
+ }
200
+
201
+ function isPlainObject(value) {
202
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
203
+ }
@@ -10,6 +10,26 @@ import {
10
10
  } from "./helpers.js";
11
11
  import { CommandError } from "../core/output.js";
12
12
 
13
+ export function normalizeTagFilter(value) {
14
+ if (value === undefined || value === null || value === "") {
15
+ return [];
16
+ }
17
+
18
+ return splitFilterValues(value).map((entry) => entry.trim()).filter(Boolean);
19
+ }
20
+
21
+ export function normalizeTagsCat(value) {
22
+ if (value === undefined || value === null || value === "") {
23
+ return undefined;
24
+ }
25
+
26
+ const normalized = String(value).toLowerCase();
27
+ if (!["meta", "subject"].includes(normalized)) {
28
+ throw new CommandError(`Unsupported tagsCat: ${value}. Use "meta" (wiki tags) or "subject" (user tags).`);
29
+ }
30
+ return normalized;
31
+ }
32
+
13
33
  export const SUBJECT_TYPE_MAP = {
14
34
  book: 1,
15
35
  anime: 2,