@chainlesschain/personal-data-hub 0.3.1 → 0.3.6

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 (60) hide show
  1. package/__tests__/adapters/email-adapter-snapshot.test.js +237 -0
  2. package/__tests__/adapters/email-adapter.test.js +1 -1
  3. package/__tests__/adapters/email-pdf-extractor.test.js +1 -1
  4. package/__tests__/adapters/email-retry-progress.test.js +1 -1
  5. package/__tests__/adapters/email-templates.test.js +1 -1
  6. package/__tests__/adapters/social-bilibili-adb-api-client.test.js +721 -0
  7. package/__tests__/adapters/social-bilibili-adb-chromium-cookies-reader.test.js +346 -0
  8. package/__tests__/adapters/social-bilibili-adb-collector.test.js +284 -0
  9. package/__tests__/adapters/social-bilibili-adb-cookies-extension.test.js +343 -0
  10. package/__tests__/adapters/social-bilibili-adb-snapshot-builder.test.js +296 -0
  11. package/__tests__/adapters/social-douyin-adb-collector.test.js +254 -0
  12. package/__tests__/adapters/social-douyin-adb-im-db-parser.test.js +304 -0
  13. package/__tests__/adapters/social-douyin-adb-snapshot-builder.test.js +216 -0
  14. package/__tests__/adapters/social-weibo-adb-api-client.test.js +362 -0
  15. package/__tests__/adapters/social-weibo-adb-collector.test.js +201 -0
  16. package/__tests__/adapters/social-weibo-adb-snapshot-builder.test.js +189 -0
  17. package/__tests__/adapters/social-xiaohongshu-adb-collector.test.js +207 -0
  18. package/__tests__/adapters/social-xiaohongshu-adb-sign.test.js +130 -0
  19. package/__tests__/adapters/system-data-android.test.js +32 -1
  20. package/__tests__/longtail-adapters.test.js +15 -2
  21. package/__tests__/shopping-adapters.test.js +96 -0
  22. package/__tests__/sign-providers.test.js +62 -0
  23. package/__tests__/travel-adapters.test.js +66 -0
  24. package/__tests__/whatsapp-adapter.test.js +5 -2
  25. package/lib/adapters/browser-history-chrome/chrome-db-reader.js +11 -1
  26. package/lib/adapters/email-imap/email-adapter.js +224 -17
  27. package/lib/adapters/messaging-telegram/index.js +15 -12
  28. package/lib/adapters/messaging-whatsapp/index.js +15 -12
  29. package/lib/adapters/shopping-taobao/index.js +161 -21
  30. package/lib/adapters/social-bilibili-adb/api-client.js +555 -0
  31. package/lib/adapters/social-bilibili-adb/chromium-cookies-reader.js +296 -0
  32. package/lib/adapters/social-bilibili-adb/collector.js +190 -0
  33. package/lib/adapters/social-bilibili-adb/cookies-extension.js +250 -0
  34. package/lib/adapters/social-bilibili-adb/index.js +51 -0
  35. package/lib/adapters/social-bilibili-adb/snapshot-builder.js +197 -0
  36. package/lib/adapters/social-douyin/index.js +4 -0
  37. package/lib/adapters/social-douyin-adb/collector.js +165 -0
  38. package/lib/adapters/social-douyin-adb/db-extension.js +281 -0
  39. package/lib/adapters/social-douyin-adb/im-db-parser.js +287 -0
  40. package/lib/adapters/social-douyin-adb/index.js +57 -0
  41. package/lib/adapters/social-douyin-adb/snapshot-builder.js +174 -0
  42. package/lib/adapters/social-weibo-adb/api-client.js +281 -0
  43. package/lib/adapters/social-weibo-adb/collector.js +169 -0
  44. package/lib/adapters/social-weibo-adb/cookies-extension.js +251 -0
  45. package/lib/adapters/social-weibo-adb/index.js +55 -0
  46. package/lib/adapters/social-weibo-adb/snapshot-builder.js +145 -0
  47. package/lib/adapters/social-xiaohongshu-adb/api-client.js +278 -0
  48. package/lib/adapters/social-xiaohongshu-adb/collector.js +158 -0
  49. package/lib/adapters/social-xiaohongshu-adb/cookies-extension.js +211 -0
  50. package/lib/adapters/social-xiaohongshu-adb/index.js +50 -0
  51. package/lib/adapters/social-xiaohongshu-adb/sign.js +90 -0
  52. package/lib/adapters/social-xiaohongshu-adb/snapshot-builder.js +126 -0
  53. package/lib/adapters/system-data-android/adapter.js +77 -3
  54. package/lib/adapters/travel-amap/index.js +16 -10
  55. package/lib/adapters/travel-ctrip/index.js +25 -9
  56. package/lib/adapters/vscode/vscode-reader.js +7 -1
  57. package/lib/sign-providers/index.js +20 -0
  58. package/lib/sign-providers/interface.js +82 -0
  59. package/lib/sign-providers/null-sign-provider.js +30 -0
  60. package/package.json +6 -1
@@ -0,0 +1,721 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Phase 1b — unit cover for BilibiliApiClient (Node port).
5
+ *
6
+ * Strategy: inject a fake `fetch` that returns canned responses per-URL.
7
+ * We don't actually hit api.bilibili.com — the goal is byte-parity with
8
+ * the Android Kotlin version, not real network testing.
9
+ *
10
+ * What we cover:
11
+ * - WBI signature: md5 stable across calls + sort order + forbidden-char
12
+ * strip + wts derivation from injected now()
13
+ * - buvid3 mint + substitution (existing buvid3 stripped, last-wins)
14
+ * - extractWbiKeyFromUrl edge cases
15
+ * - extractUid edge cases
16
+ * - 4 endpoint parse — happy-path response shapes mirroring Bilibili's
17
+ * - Partial-failure: any endpoint returns [] on transport / code-non-zero
18
+ * - lastErrorCode / lastErrorMessage set on failure
19
+ * - Endpoint URL contracts: required query params present
20
+ */
21
+
22
+ import { describe, it, expect, beforeEach } from "vitest";
23
+
24
+ const {
25
+ BilibiliApiClient,
26
+ extractUid,
27
+ _internals,
28
+ } = require("../../lib/adapters/social-bilibili-adb/api-client");
29
+ const {
30
+ extractWbiKeyFromUrl,
31
+ substituteBuvid3,
32
+ md5Hex,
33
+ stripForbiddenChars,
34
+ signUrl,
35
+ WBI_MIXIN_KEY_TABLE,
36
+ } = _internals;
37
+
38
+ // ─── Pure helpers ───────────────────────────────────────────────────────
39
+
40
+ describe("extractWbiKeyFromUrl", () => {
41
+ it("extracts hex from CDN URL", () => {
42
+ expect(
43
+ extractWbiKeyFromUrl("https://i0.hdslb.com/bfs/wbi/abc123.png"),
44
+ ).toBe("abc123");
45
+ });
46
+
47
+ it("handles missing extension → null", () => {
48
+ expect(extractWbiKeyFromUrl("https://i0.hdslb.com/bfs/wbi/abc123")).toBe(null);
49
+ });
50
+
51
+ it("handles missing slash → null (no path component)", () => {
52
+ expect(extractWbiKeyFromUrl("abc123.png")).toBe(null);
53
+ });
54
+
55
+ it("rejects empty / null", () => {
56
+ expect(extractWbiKeyFromUrl("")).toBe(null);
57
+ expect(extractWbiKeyFromUrl(null)).toBe(null);
58
+ expect(extractWbiKeyFromUrl(undefined)).toBe(null);
59
+ });
60
+ });
61
+
62
+ describe("substituteBuvid3", () => {
63
+ it("appends buvid3 when cookie has none", () => {
64
+ expect(substituteBuvid3("SESSDATA=abc; bili_jct=csrf", "newB3")).toBe(
65
+ "SESSDATA=abc; bili_jct=csrf; buvid3=newB3",
66
+ );
67
+ });
68
+
69
+ it("replaces existing buvid3 (last-wins)", () => {
70
+ expect(
71
+ substituteBuvid3("SESSDATA=abc; buvid3=oldB3; bili_jct=csrf", "newB3"),
72
+ ).toBe("SESSDATA=abc; bili_jct=csrf; buvid3=newB3");
73
+ });
74
+
75
+ it("handles cookie with only buvid3", () => {
76
+ expect(substituteBuvid3("buvid3=oldB3", "newB3")).toBe("buvid3=newB3");
77
+ });
78
+
79
+ it("handles empty cookie", () => {
80
+ expect(substituteBuvid3("", "newB3")).toBe("buvid3=newB3");
81
+ });
82
+ });
83
+
84
+ describe("stripForbiddenChars", () => {
85
+ it("strips !'()*", () => {
86
+ expect(stripForbiddenChars("hello!world'(test)*end")).toBe(
87
+ "helloworldtestend",
88
+ );
89
+ });
90
+
91
+ it("preserves other chars", () => {
92
+ expect(stripForbiddenChars("normal text 123 中文")).toBe(
93
+ "normal text 123 中文",
94
+ );
95
+ });
96
+
97
+ it("handles non-string", () => {
98
+ expect(stripForbiddenChars(42)).toBe("42");
99
+ });
100
+ });
101
+
102
+ describe("md5Hex", () => {
103
+ it("returns stable digest for known input", () => {
104
+ expect(md5Hex("hello")).toBe("5d41402abc4b2a76b9719d911017c592");
105
+ expect(md5Hex("")).toBe("d41d8cd98f00b204e9800998ecf8427e");
106
+ });
107
+
108
+ it("handles utf-8 chars", () => {
109
+ expect(md5Hex("中文")).toBe(md5Hex("中文")); // stable
110
+ });
111
+ });
112
+
113
+ // ─── signUrl ────────────────────────────────────────────────────────────
114
+
115
+ describe("signUrl", () => {
116
+ it("appends wts + w_rid + preserves existing params", () => {
117
+ const url = new URL("https://api.bilibili.com/x/foo");
118
+ url.searchParams.set("ps", "30");
119
+ url.searchParams.set("type", "archive");
120
+ const signed = signUrl(url, "MIXIN_KEY_32_CHARS_LONG_AAAAAAA12", {
121
+ now: () => 1716383021000,
122
+ });
123
+ expect(signed.searchParams.get("wts")).toBe("1716383021");
124
+ expect(signed.searchParams.get("w_rid")).toMatch(/^[0-9a-f]{32}$/);
125
+ expect(signed.searchParams.get("ps")).toBe("30");
126
+ expect(signed.searchParams.get("type")).toBe("archive");
127
+ });
128
+
129
+ it("sorts existing params + wts alphabetically before md5", () => {
130
+ // Same params, different insertion order → same w_rid
131
+ const u1 = new URL("https://api.bilibili.com/x/foo");
132
+ u1.searchParams.set("z", "1");
133
+ u1.searchParams.set("a", "2");
134
+ const u2 = new URL("https://api.bilibili.com/x/foo");
135
+ u2.searchParams.set("a", "2");
136
+ u2.searchParams.set("z", "1");
137
+ const mixin = "M".repeat(32);
138
+ const now = () => 1716383021000;
139
+ const s1 = signUrl(u1, mixin, { now });
140
+ const s2 = signUrl(u2, mixin, { now });
141
+ expect(s1.searchParams.get("w_rid")).toBe(s2.searchParams.get("w_rid"));
142
+ });
143
+
144
+ it("strips forbidden chars from values before signing", () => {
145
+ const u1 = new URL("https://api.bilibili.com/x/foo");
146
+ u1.searchParams.set("title", "hello!world");
147
+ const u2 = new URL("https://api.bilibili.com/x/foo");
148
+ u2.searchParams.set("title", "helloworld");
149
+ const mixin = "M".repeat(32);
150
+ const now = () => 1716383021000;
151
+ const s1 = signUrl(u1, mixin, { now });
152
+ const s2 = signUrl(u2, mixin, { now });
153
+ // After stripping `!`, the signature input should match
154
+ expect(s1.searchParams.get("w_rid")).toBe(s2.searchParams.get("w_rid"));
155
+ });
156
+
157
+ it("uses Math.floor(now/1000) as wts", () => {
158
+ const url = new URL("https://api.bilibili.com/x/foo");
159
+ const signed = signUrl(url, "M".repeat(32), {
160
+ now: () => 1716383021999, // .999 ms — should still floor to 1716383021
161
+ });
162
+ expect(signed.searchParams.get("wts")).toBe("1716383021");
163
+ });
164
+ });
165
+
166
+ // ─── extractUid ─────────────────────────────────────────────────────────
167
+
168
+ describe("extractUid", () => {
169
+ it("extracts from full Bilibili cookie", () => {
170
+ expect(
171
+ extractUid(
172
+ "SESSDATA=abc; bili_jct=csrf; DedeUserID=1234567890; DedeUserID__ckMd5=xx; buvid3=b3",
173
+ ),
174
+ ).toBe(1234567890);
175
+ });
176
+
177
+ it("returns null when DedeUserID missing", () => {
178
+ expect(extractUid("SESSDATA=abc; bili_jct=csrf")).toBe(null);
179
+ });
180
+
181
+ it("returns null when DedeUserID=0 (mid-logout)", () => {
182
+ expect(extractUid("DedeUserID=0; SESSDATA=abc")).toBe(null);
183
+ });
184
+
185
+ it("handles whitespace around values", () => {
186
+ expect(extractUid("SESSDATA=abc; DedeUserID=42; ")).toBe(42);
187
+ });
188
+
189
+ it("rejects non-string", () => {
190
+ expect(extractUid(null)).toBe(null);
191
+ expect(extractUid(undefined)).toBe(null);
192
+ expect(extractUid({})).toBe(null);
193
+ });
194
+ });
195
+
196
+ // ─── BilibiliApiClient ──────────────────────────────────────────────────
197
+
198
+ function makeClient(responses) {
199
+ /**
200
+ * Fake fetch matches requests by URL substring → returns Response-like
201
+ * object with text() + json() + ok + status. `responses` is an array
202
+ * of [substring, payload] tuples.
203
+ */
204
+ const calls = [];
205
+ const fakeFetch = async (urlStr, opts) => {
206
+ calls.push({ url: urlStr, opts });
207
+ for (const [pattern, payload] of responses) {
208
+ if (urlStr.includes(pattern)) {
209
+ const resolved = typeof payload === "function" ? await payload(urlStr, opts) : payload;
210
+ return {
211
+ ok: resolved.status == null || resolved.status === 200,
212
+ status: resolved.status || 200,
213
+ text: async () => resolved.body,
214
+ json: async () => JSON.parse(resolved.body),
215
+ };
216
+ }
217
+ }
218
+ throw new Error("fake fetch: no scripted response for " + urlStr);
219
+ };
220
+ const client = new BilibiliApiClient({
221
+ fetch: fakeFetch,
222
+ now: () => 1716383021000,
223
+ });
224
+ return { client, calls };
225
+ }
226
+
227
+ const FAKE_COOKIE = "SESSDATA=abc; bili_jct=csrf; DedeUserID=1234567890; DedeUserID__ckMd5=cm; buvid3=oldB3";
228
+
229
+ const NAV_RESPONSE_BODY = JSON.stringify({
230
+ code: -101,
231
+ data: {
232
+ wbi_img: {
233
+ img_url: "https://i0.hdslb.com/bfs/wbi/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.png",
234
+ sub_url: "https://i0.hdslb.com/bfs/wbi/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.png",
235
+ },
236
+ },
237
+ });
238
+
239
+ const SPI_RESPONSE_BODY = JSON.stringify({
240
+ code: 0,
241
+ data: { b_3: "MINTED_BUVID3" },
242
+ });
243
+
244
+ describe("BilibiliApiClient — bootstrap (mint + nav)", () => {
245
+ it("mints buvid3 once and caches", async () => {
246
+ const { client, calls } = makeClient([
247
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
248
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
249
+ ["history/cursor", { body: JSON.stringify({ code: 0, data: { list: [] } }) }],
250
+ ]);
251
+ await client.fetchHistory(FAKE_COOKIE);
252
+ await client.fetchHistory(FAKE_COOKIE);
253
+ const spiCalls = calls.filter((c) => c.url.includes("finger/spi"));
254
+ expect(spiCalls).toHaveLength(1); // cached
255
+ });
256
+
257
+ it("derives mixin key from img+sub keys", async () => {
258
+ const { client } = makeClient([
259
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
260
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
261
+ ]);
262
+ const mixin = await client._ensureWbiMixinKey();
263
+ expect(mixin).toBeTruthy();
264
+ expect(mixin).toHaveLength(32);
265
+ });
266
+
267
+ it("substitutes minted buvid3 into outgoing Cookie header", async () => {
268
+ const { client, calls } = makeClient([
269
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
270
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
271
+ ["history/cursor", { body: JSON.stringify({ code: 0, data: { list: [] } }) }],
272
+ ]);
273
+ await client.fetchHistory(FAKE_COOKIE);
274
+ const histCall = calls.find((c) => c.url.includes("history/cursor"));
275
+ expect(histCall).toBeTruthy();
276
+ const sentCookie = histCall.opts.headers.Cookie;
277
+ expect(sentCookie).toContain("buvid3=MINTED_BUVID3");
278
+ expect(sentCookie).not.toContain("buvid3=oldB3");
279
+ });
280
+
281
+ it("signs URLs with wts + w_rid", async () => {
282
+ const { client, calls } = makeClient([
283
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
284
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
285
+ ["history/cursor", { body: JSON.stringify({ code: 0, data: { list: [] } }) }],
286
+ ]);
287
+ await client.fetchHistory(FAKE_COOKIE);
288
+ const histCall = calls.find((c) => c.url.includes("history/cursor"));
289
+ expect(histCall.url).toMatch(/wts=\d+/);
290
+ expect(histCall.url).toMatch(/w_rid=[0-9a-f]{32}/);
291
+ });
292
+
293
+ it("degrades gracefully when nav fails", async () => {
294
+ const { client, calls } = makeClient([
295
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
296
+ ["web-interface/nav", { status: 500, body: "Internal Error" }],
297
+ ["history/cursor", { body: JSON.stringify({ code: 0, data: { list: [] } }) }],
298
+ ]);
299
+ const result = await client.fetchHistory(FAKE_COOKIE);
300
+ expect(result).toEqual([]); // succeeds but with unsigned URL → server might 412
301
+ const histCall = calls.find((c) => c.url.includes("history/cursor"));
302
+ expect(histCall.url).not.toMatch(/w_rid=/); // no signature when nav failed
303
+ });
304
+ });
305
+
306
+ // ─── fetchHistory ───────────────────────────────────────────────────────
307
+
308
+ describe("BilibiliApiClient.fetchHistory", () => {
309
+ it("parses history response", async () => {
310
+ const { client } = makeClient([
311
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
312
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
313
+ [
314
+ "history/cursor",
315
+ {
316
+ body: JSON.stringify({
317
+ code: 0,
318
+ data: {
319
+ list: [
320
+ {
321
+ history: { bvid: "BV1xx", oid: 100 },
322
+ title: "Test Video 1",
323
+ view_at: 1716383021,
324
+ duration: 300,
325
+ owner: { name: "uploader1", mid: 999 },
326
+ part: "Part 1",
327
+ },
328
+ {
329
+ history: { bvid: "BV2yy" },
330
+ title: "Test Video 2",
331
+ view_at: 1716383022,
332
+ },
333
+ ],
334
+ },
335
+ }),
336
+ },
337
+ ],
338
+ ]);
339
+ const history = await client.fetchHistory(FAKE_COOKIE);
340
+ expect(history).toHaveLength(2);
341
+ expect(history[0]).toMatchObject({
342
+ bvid: "BV1xx",
343
+ avid: 100,
344
+ title: "Test Video 1",
345
+ viewAt: 1716383021,
346
+ duration: 300,
347
+ uploader: "uploader1",
348
+ uploaderMid: 999,
349
+ part: "Part 1",
350
+ });
351
+ expect(history[1].bvid).toBe("BV2yy");
352
+ expect(history[1].uploader).toBe(null);
353
+ });
354
+
355
+ it("respects limit", async () => {
356
+ const items = Array.from({ length: 100 }, (_, i) => ({
357
+ history: { bvid: `BV${i}` },
358
+ title: "T",
359
+ view_at: 1,
360
+ }));
361
+ const { client } = makeClient([
362
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
363
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
364
+ ["history/cursor", { body: JSON.stringify({ code: 0, data: { list: items } }) }],
365
+ ]);
366
+ const history = await client.fetchHistory(FAKE_COOKIE, { limit: 5 });
367
+ expect(history).toHaveLength(5);
368
+ });
369
+
370
+ it("returns [] when code != 0 + sets lastError", async () => {
371
+ const { client } = makeClient([
372
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
373
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
374
+ [
375
+ "history/cursor",
376
+ { body: JSON.stringify({ code: -412, message: "anti-spider" }) },
377
+ ],
378
+ ]);
379
+ const history = await client.fetchHistory(FAKE_COOKIE);
380
+ expect(history).toEqual([]);
381
+ expect(client.lastErrorCode).toBe(-412);
382
+ expect(client.lastErrorMessage).toBe("anti-spider");
383
+ });
384
+
385
+ it("returns [] on HTTP error + sets lastError", async () => {
386
+ const { client } = makeClient([
387
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
388
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
389
+ ["history/cursor", { status: 503, body: "Service Unavailable" }],
390
+ ]);
391
+ const history = await client.fetchHistory(FAKE_COOKIE);
392
+ expect(history).toEqual([]);
393
+ expect(client.lastErrorCode).toBe(503);
394
+ });
395
+
396
+ it("includes required query params (type=archive, ps=30)", async () => {
397
+ const { client, calls } = makeClient([
398
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
399
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
400
+ ["history/cursor", { body: JSON.stringify({ code: 0, data: { list: [] } }) }],
401
+ ]);
402
+ await client.fetchHistory(FAKE_COOKIE);
403
+ const histCall = calls.find((c) => c.url.includes("history/cursor"));
404
+ expect(histCall.url).toContain("type=archive");
405
+ expect(histCall.url).toContain("ps=30");
406
+ });
407
+ });
408
+
409
+ // ─── fetchFavourites ────────────────────────────────────────────────────
410
+
411
+ describe("BilibiliApiClient.fetchFavourites", () => {
412
+ it("walks each folder and aggregates items", async () => {
413
+ const { client } = makeClient([
414
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
415
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
416
+ [
417
+ "fav/folder/created/list-all",
418
+ {
419
+ body: JSON.stringify({
420
+ code: 0,
421
+ data: { list: [{ id: 101, title: "Folder A" }, { id: 102, title: "Folder B" }] },
422
+ }),
423
+ },
424
+ ],
425
+ [
426
+ "fav/resource/list",
427
+ async (url) => {
428
+ if (url.includes("media_id=101")) {
429
+ return {
430
+ body: JSON.stringify({
431
+ code: 0,
432
+ data: {
433
+ medias: [
434
+ {
435
+ bvid: "BVf1",
436
+ title: "Fav in A",
437
+ fav_time: 1716383021,
438
+ upper: { name: "upA" },
439
+ },
440
+ ],
441
+ },
442
+ }),
443
+ };
444
+ }
445
+ return {
446
+ body: JSON.stringify({
447
+ code: 0,
448
+ data: {
449
+ medias: [
450
+ { bvid: "BVf2", title: "Fav in B", fav_time: 1716383022, upper: { name: "upB" } },
451
+ ],
452
+ },
453
+ }),
454
+ };
455
+ },
456
+ ],
457
+ ]);
458
+ const favs = await client.fetchFavourites(FAKE_COOKIE, 1234567890);
459
+ expect(favs).toHaveLength(2);
460
+ expect(favs[0].folderName).toBe("Folder A");
461
+ expect(favs[1].folderName).toBe("Folder B");
462
+ // fav_time is unix seconds → savedAt is unix ms
463
+ expect(favs[0].savedAt).toBe(1716383021000);
464
+ });
465
+
466
+ it("returns [] when folders endpoint fails", async () => {
467
+ const { client } = makeClient([
468
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
469
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
470
+ [
471
+ "fav/folder/created/list-all",
472
+ { body: JSON.stringify({ code: -400, message: "bad request" }) },
473
+ ],
474
+ ]);
475
+ const favs = await client.fetchFavourites(FAKE_COOKIE, 1234567890);
476
+ expect(favs).toEqual([]);
477
+ });
478
+
479
+ it("includes platform=web on per-folder items request", async () => {
480
+ const { client, calls } = makeClient([
481
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
482
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
483
+ [
484
+ "fav/folder/created/list-all",
485
+ {
486
+ body: JSON.stringify({
487
+ code: 0,
488
+ data: { list: [{ id: 101, title: "F" }] },
489
+ }),
490
+ },
491
+ ],
492
+ [
493
+ "fav/resource/list",
494
+ { body: JSON.stringify({ code: 0, data: { medias: [] } }) },
495
+ ],
496
+ ]);
497
+ await client.fetchFavourites(FAKE_COOKIE, 1234567890);
498
+ const itemsCall = calls.find((c) => c.url.includes("fav/resource/list"));
499
+ expect(itemsCall.url).toContain("platform=web");
500
+ });
501
+ });
502
+
503
+ // ─── fetchDynamics ──────────────────────────────────────────────────────
504
+
505
+ describe("BilibiliApiClient.fetchDynamics", () => {
506
+ it("parses dynamic feed", async () => {
507
+ const { client } = makeClient([
508
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
509
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
510
+ [
511
+ "web-dynamic/v1/feed/all",
512
+ {
513
+ body: JSON.stringify({
514
+ code: 0,
515
+ data: {
516
+ items: [
517
+ {
518
+ id_str: "dyn-1",
519
+ type: "DYNAMIC_TYPE_AV",
520
+ modules: {
521
+ module_author: {
522
+ mid: 999,
523
+ name: "author-x",
524
+ pub_ts: 1716383021,
525
+ },
526
+ module_dynamic: {
527
+ desc: { text: "hello world" },
528
+ },
529
+ },
530
+ },
531
+ ],
532
+ },
533
+ }),
534
+ },
535
+ ],
536
+ ]);
537
+ const dyns = await client.fetchDynamics(FAKE_COOKIE);
538
+ expect(dyns).toHaveLength(1);
539
+ expect(dyns[0]).toMatchObject({
540
+ rid: "dyn-1",
541
+ summary: "hello world",
542
+ dynamicType: "av",
543
+ publishedAt: 1716383021000,
544
+ authorMid: 999,
545
+ authorName: "author-x",
546
+ });
547
+ });
548
+
549
+ it("falls back to archive.title when desc.text missing", async () => {
550
+ const { client } = makeClient([
551
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
552
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
553
+ [
554
+ "web-dynamic/v1/feed/all",
555
+ {
556
+ body: JSON.stringify({
557
+ code: 0,
558
+ data: {
559
+ items: [
560
+ {
561
+ id_str: "dyn-2",
562
+ type: "DYNAMIC_TYPE_AV",
563
+ modules: {
564
+ module_author: { mid: 1, name: "x", pub_ts: 1 },
565
+ module_dynamic: { major: { archive: { title: "Archive Title" } } },
566
+ },
567
+ },
568
+ ],
569
+ },
570
+ }),
571
+ },
572
+ ],
573
+ ]);
574
+ const dyns = await client.fetchDynamics(FAKE_COOKIE);
575
+ expect(dyns[0].summary).toBe("Archive Title");
576
+ });
577
+
578
+ it("includes timezone_offset=-480", async () => {
579
+ const { client, calls } = makeClient([
580
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
581
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
582
+ [
583
+ "web-dynamic/v1/feed/all",
584
+ { body: JSON.stringify({ code: 0, data: { items: [] } }) },
585
+ ],
586
+ ]);
587
+ await client.fetchDynamics(FAKE_COOKIE);
588
+ const dynCall = calls.find((c) => c.url.includes("web-dynamic"));
589
+ expect(decodeURIComponent(dynCall.url)).toContain("timezone_offset=-480");
590
+ });
591
+ });
592
+
593
+ // ─── fetchFollows ───────────────────────────────────────────────────────
594
+
595
+ describe("BilibiliApiClient.fetchFollows", () => {
596
+ it("parses following list", async () => {
597
+ const { client } = makeClient([
598
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
599
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
600
+ [
601
+ "relation/followings",
602
+ {
603
+ body: JSON.stringify({
604
+ code: 0,
605
+ data: {
606
+ list: [
607
+ {
608
+ mid: 42,
609
+ uname: "Friend1",
610
+ face: "https://face.png",
611
+ sign: "hi",
612
+ mtime: 1716383021,
613
+ },
614
+ ],
615
+ },
616
+ }),
617
+ },
618
+ ],
619
+ ]);
620
+ const fols = await client.fetchFollows(FAKE_COOKIE, 1234567890);
621
+ expect(fols).toHaveLength(1);
622
+ expect(fols[0]).toMatchObject({
623
+ mid: 42,
624
+ uname: "Friend1",
625
+ face: "https://face.png",
626
+ sign: "hi",
627
+ followedAt: 1716383021000,
628
+ });
629
+ });
630
+
631
+ it("skips mid=0 entries", async () => {
632
+ const { client } = makeClient([
633
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
634
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
635
+ [
636
+ "relation/followings",
637
+ {
638
+ body: JSON.stringify({
639
+ code: 0,
640
+ data: {
641
+ list: [
642
+ { mid: 0, uname: "Ghost" },
643
+ { mid: 1, uname: "Real" },
644
+ ],
645
+ },
646
+ }),
647
+ },
648
+ ],
649
+ ]);
650
+ const fols = await client.fetchFollows(FAKE_COOKIE, 1234567890);
651
+ expect(fols).toHaveLength(1);
652
+ expect(fols[0].uname).toBe("Real");
653
+ });
654
+
655
+ it("includes vmid + order params", async () => {
656
+ const { client, calls } = makeClient([
657
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
658
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
659
+ [
660
+ "relation/followings",
661
+ { body: JSON.stringify({ code: 0, data: { list: [] } }) },
662
+ ],
663
+ ]);
664
+ await client.fetchFollows(FAKE_COOKIE, 1234567890);
665
+ const followsCall = calls.find((c) => c.url.includes("relation/followings"));
666
+ expect(followsCall.url).toContain("vmid=1234567890");
667
+ expect(followsCall.url).toContain("order=desc");
668
+ expect(followsCall.url).toContain("order_type=attention");
669
+ });
670
+ });
671
+
672
+ // ─── test seams ─────────────────────────────────────────────────────────
673
+
674
+ describe("BilibiliApiClient — test seams", () => {
675
+ it("setMintedBuvid3ForTest bypasses /spi network call", async () => {
676
+ const { client, calls } = makeClient([
677
+ ["finger/spi", () => {
678
+ throw new Error("should not call /spi");
679
+ }],
680
+ ["web-interface/nav", { body: NAV_RESPONSE_BODY }],
681
+ ["history/cursor", { body: JSON.stringify({ code: 0, data: { list: [] } }) }],
682
+ ]);
683
+ client.setMintedBuvid3ForTest("PRE_SEEDED_B3");
684
+ await client.fetchHistory(FAKE_COOKIE);
685
+ const histCall = calls.find((c) => c.url.includes("history/cursor"));
686
+ expect(histCall.opts.headers.Cookie).toContain("buvid3=PRE_SEEDED_B3");
687
+ });
688
+
689
+ it("setWbiMixinKeyForTest bypasses /nav network call", async () => {
690
+ const { client, calls } = makeClient([
691
+ ["finger/spi", { body: SPI_RESPONSE_BODY }],
692
+ ["web-interface/nav", () => {
693
+ throw new Error("should not call /nav");
694
+ }],
695
+ ["history/cursor", { body: JSON.stringify({ code: 0, data: { list: [] } }) }],
696
+ ]);
697
+ client.setWbiMixinKeyForTest("M".repeat(32));
698
+ await client.fetchHistory(FAKE_COOKIE);
699
+ const histCall = calls.find((c) => c.url.includes("history/cursor"));
700
+ expect(histCall.url).toMatch(/w_rid=[0-9a-f]{32}/);
701
+ });
702
+ });
703
+
704
+ // ─── WBI table contract ─────────────────────────────────────────────────
705
+
706
+ describe("WBI_MIXIN_KEY_TABLE", () => {
707
+ it("is frozen", () => {
708
+ expect(Object.isFrozen(WBI_MIXIN_KEY_TABLE)).toBe(true);
709
+ });
710
+
711
+ it("has exactly 64 entries", () => {
712
+ expect(WBI_MIXIN_KEY_TABLE.length).toBe(64);
713
+ });
714
+
715
+ it("all indexes are in [0, 63]", () => {
716
+ for (const i of WBI_MIXIN_KEY_TABLE) {
717
+ expect(i).toBeGreaterThanOrEqual(0);
718
+ expect(i).toBeLessThanOrEqual(63);
719
+ }
720
+ });
721
+ });