@chainlesschain/personal-data-hub 0.4.28 → 0.4.30

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 (204) hide show
  1. package/README.md +13 -5
  2. package/lib/adapters/social-douyin-adb/usage-profile-reader.js +253 -0
  3. package/lib/adapters/social-douyin-adb/watch-history-reader.js +104 -31
  4. package/lib/adapters/social-toutiao-adb/article-reader.js +202 -0
  5. package/lib/analysis-skills/overview.js +24 -4
  6. package/lib/analysis-skills/spending.js +63 -2
  7. package/lib/analysis-skills/timeline.js +11 -6
  8. package/lib/prompt-builder.js +15 -1
  9. package/lib/query-parser.js +38 -8
  10. package/package.json +4 -1
  11. package/__tests__/adapter-guide.test.js +0 -47
  12. package/__tests__/adapter-spec.test.js +0 -78
  13. package/__tests__/adapters/ai-chat-cookie-capture-spec.test.js +0 -211
  14. package/__tests__/adapters/ai-chat-health-checker.test.js +0 -262
  15. package/__tests__/adapters/ai-chat-history.test.js +0 -396
  16. package/__tests__/adapters/ai-chat-http-client.test.js +0 -242
  17. package/__tests__/adapters/ai-chat-vendors.test.js +0 -874
  18. package/__tests__/adapters/alipay-bill-adapter.test.js +0 -538
  19. package/__tests__/adapters/apple-health.test.js +0 -95
  20. package/__tests__/adapters/bank-family.test.js +0 -125
  21. package/__tests__/adapters/biz-tianyancha.test.js +0 -159
  22. package/__tests__/adapters/browser-history-chrome.test.js +0 -377
  23. package/__tests__/adapters/browser-history-edge.test.js +0 -159
  24. package/__tests__/adapters/car-mercedesme.test.js +0 -74
  25. package/__tests__/adapters/doc-baidu-netdisk.test.js +0 -102
  26. package/__tests__/adapters/doc-camscanner.test.js +0 -147
  27. package/__tests__/adapters/doc-platforms.test.js +0 -177
  28. package/__tests__/adapters/edu-huawei-learning-live.test.js +0 -198
  29. package/__tests__/adapters/edu-zuoyebang-live.test.js +0 -226
  30. package/__tests__/adapters/email-adapter-snapshot.test.js +0 -237
  31. package/__tests__/adapters/email-adapter.test.js +0 -742
  32. package/__tests__/adapters/email-classifier.test.js +0 -347
  33. package/__tests__/adapters/email-imap-session.test.js +0 -334
  34. package/__tests__/adapters/email-parser.test.js +0 -244
  35. package/__tests__/adapters/email-pdf-extractor.test.js +0 -529
  36. package/__tests__/adapters/email-providers.test.js +0 -84
  37. package/__tests__/adapters/email-retry-progress.test.js +0 -294
  38. package/__tests__/adapters/email-templates.test.js +0 -822
  39. package/__tests__/adapters/family-23-collectors-scaffold.test.js +0 -182
  40. package/__tests__/adapters/finance-alipay-live.test.js +0 -258
  41. package/__tests__/adapters/finance-dcep.test.js +0 -74
  42. package/__tests__/adapters/fitness-joyrun.test.js +0 -82
  43. package/__tests__/adapters/game-genshin-live.test.js +0 -238
  44. package/__tests__/adapters/game-genshin-scaffold.test.js +0 -108
  45. package/__tests__/adapters/game-honor-of-kings-live.test.js +0 -230
  46. package/__tests__/adapters/git-activity.test.js +0 -222
  47. package/__tests__/adapters/gov-12123.test.js +0 -103
  48. package/__tests__/adapters/gov-ixiamen.test.js +0 -150
  49. package/__tests__/adapters/gov-tax.test.js +0 -135
  50. package/__tests__/adapters/health-meiyou.test.js +0 -125
  51. package/__tests__/adapters/local-files.test.js +0 -264
  52. package/__tests__/adapters/local-im-pc.test.js +0 -154
  53. package/__tests__/adapters/messaging-whatsapp.test.js +0 -289
  54. package/__tests__/adapters/music-kugou.test.js +0 -187
  55. package/__tests__/adapters/music-qq.test.js +0 -112
  56. package/__tests__/adapters/netease-music-live.test.js +0 -244
  57. package/__tests__/adapters/netease-music.test.js +0 -74
  58. package/__tests__/adapters/pc-local-discovery.test.js +0 -141
  59. package/__tests__/adapters/qq-pc-direct-read.test.js +0 -227
  60. package/__tests__/adapters/reading-family.test.js +0 -108
  61. package/__tests__/adapters/recruit-boss.test.js +0 -180
  62. package/__tests__/adapters/shell-history.test.js +0 -180
  63. package/__tests__/adapters/shopping-base.test.js +0 -179
  64. package/__tests__/adapters/shopping-dianping.test.js +0 -239
  65. package/__tests__/adapters/social-bilibili-adb-api-client.test.js +0 -721
  66. package/__tests__/adapters/social-bilibili-adb-chromium-cookies-reader.test.js +0 -346
  67. package/__tests__/adapters/social-bilibili-adb-collector.test.js +0 -284
  68. package/__tests__/adapters/social-bilibili-adb-cookies-extension.test.js +0 -343
  69. package/__tests__/adapters/social-bilibili-adb-snapshot-builder.test.js +0 -296
  70. package/__tests__/adapters/social-csdn.test.js +0 -175
  71. package/__tests__/adapters/social-dongchedi.test.js +0 -165
  72. package/__tests__/adapters/social-douyin-adb-aweme-detail.test.js +0 -165
  73. package/__tests__/adapters/social-douyin-adb-collector.test.js +0 -254
  74. package/__tests__/adapters/social-douyin-adb-db-extension.test.js +0 -114
  75. package/__tests__/adapters/social-douyin-adb-im-db-parser.test.js +0 -304
  76. package/__tests__/adapters/social-douyin-adb-snapshot-builder.test.js +0 -216
  77. package/__tests__/adapters/social-douyin-adb-watch-history.test.js +0 -192
  78. package/__tests__/adapters/social-kuaishou-adb-api-client.test.js +0 -496
  79. package/__tests__/adapters/social-kuaishou-adb-collector.test.js +0 -276
  80. package/__tests__/adapters/social-kuaishou-adb-cookies-extension.test.js +0 -152
  81. package/__tests__/adapters/social-kuaishou-adb-snapshot-builder.test.js +0 -178
  82. package/__tests__/adapters/social-toutiao-adb-account-reader.test.js +0 -135
  83. package/__tests__/adapters/social-toutiao-adb-api-client.test.js +0 -626
  84. package/__tests__/adapters/social-toutiao-adb-collector.test.js +0 -378
  85. package/__tests__/adapters/social-toutiao-adb-cookies-extension.test.js +0 -193
  86. package/__tests__/adapters/social-toutiao-adb-snapshot-builder.test.js +0 -196
  87. package/__tests__/adapters/social-toutiao-kuaishou-scaffold.test.js +0 -311
  88. package/__tests__/adapters/social-weibo-adb-api-client.test.js +0 -362
  89. package/__tests__/adapters/social-weibo-adb-collector.test.js +0 -201
  90. package/__tests__/adapters/social-weibo-adb-cookies-extension.test.js +0 -167
  91. package/__tests__/adapters/social-weibo-adb-snapshot-builder.test.js +0 -189
  92. package/__tests__/adapters/social-xiaohongshu-adb-api-client.test.js +0 -431
  93. package/__tests__/adapters/social-xiaohongshu-adb-collector.test.js +0 -207
  94. package/__tests__/adapters/social-xiaohongshu-adb-cookies-extension.test.js +0 -0
  95. package/__tests__/adapters/social-xiaohongshu-adb-sign-provider-injection.test.js +0 -351
  96. package/__tests__/adapters/social-xiaohongshu-adb-sign.test.js +0 -130
  97. package/__tests__/adapters/social-xiaohongshu-adb-snapshot-builder.test.js +0 -200
  98. package/__tests__/adapters/social-zhihu.test.js +0 -246
  99. package/__tests__/adapters/system-data-adapter.test.js +0 -443
  100. package/__tests__/adapters/system-data-android-ingest.test.js +0 -144
  101. package/__tests__/adapters/system-data-android.test.js +0 -519
  102. package/__tests__/adapters/system-data-disclosure.test.js +0 -153
  103. package/__tests__/adapters/travel-12306.test.js +0 -512
  104. package/__tests__/adapters/travel-amap.test.js +0 -219
  105. package/__tests__/adapters/travel-baidu-map.test.js +0 -305
  106. package/__tests__/adapters/travel-base.test.js +0 -205
  107. package/__tests__/adapters/travel-ctrip.test.js +0 -377
  108. package/__tests__/adapters/travel-didi-consumer.test.js +0 -66
  109. package/__tests__/adapters/travel-didi.test.js +0 -204
  110. package/__tests__/adapters/travel-tencent-map.test.js +0 -207
  111. package/__tests__/adapters/travel-tongcheng.test.js +0 -289
  112. package/__tests__/adapters/video-platforms.test.js +0 -152
  113. package/__tests__/adapters/video-xigua.test.js +0 -106
  114. package/__tests__/adapters/vscode.test.js +0 -299
  115. package/__tests__/adapters/wechat-bootstrap.test.js +0 -240
  116. package/__tests__/adapters/wechat-env-probe.test.js +0 -162
  117. package/__tests__/adapters/wechat-frida-agent.test.js +0 -322
  118. package/__tests__/adapters/wechat-frida-integration.test.js +0 -149
  119. package/__tests__/adapters/wechat-frida-key-provider.test.js +0 -188
  120. package/__tests__/adapters/wechat-md5-key-provider.test.js +0 -101
  121. package/__tests__/adapters/wechat-pc-direct-read.test.js +0 -365
  122. package/__tests__/adapters/wechat-pc-group-topic.test.js +0 -63
  123. package/__tests__/adapters/wechat-pc-v4-sidecar.test.js +0 -72
  124. package/__tests__/adapters/weread.test.js +0 -123
  125. package/__tests__/adapters/wework-pc.test.js +0 -124
  126. package/__tests__/adapters/win-recent.test.js +0 -192
  127. package/__tests__/analysis-skills.test.js +0 -679
  128. package/__tests__/analysis.test.js +0 -1845
  129. package/__tests__/audio-ximalaya-snapshot.test.js +0 -279
  130. package/__tests__/batch.test.js +0 -133
  131. package/__tests__/bridges-cc-kg.test.js +0 -231
  132. package/__tests__/bridges-cc-llm.test.js +0 -191
  133. package/__tests__/bridges-cc-rag.test.js +0 -162
  134. package/__tests__/categories.test.js +0 -92
  135. package/__tests__/e2e/ai-chat-cross-source-journey.test.js +0 -213
  136. package/__tests__/e2e/full-user-journey.test.js +0 -188
  137. package/__tests__/e2e/local-data-adapters-cli.e2e.test.js +0 -146
  138. package/__tests__/entity-resolver-ingest-hook.test.js +0 -177
  139. package/__tests__/entity-resolver-stages.test.js +0 -411
  140. package/__tests__/entity-resolver-vault.test.js +0 -249
  141. package/__tests__/entity-resolver.test.js +0 -526
  142. package/__tests__/fitness-keep-snapshot.test.js +0 -224
  143. package/__tests__/fixtures/entity-resolver-200-mock.json +0 -96
  144. package/__tests__/ids.test.js +0 -45
  145. package/__tests__/integration/ai-chat-history-registry.test.js +0 -228
  146. package/__tests__/integration/aichat-wizard-end-to-end.test.js +0 -282
  147. package/__tests__/integration/cross-adapter-pipelines.test.js +0 -396
  148. package/__tests__/integration/local-data-adapters-pipeline.test.js +0 -373
  149. package/__tests__/integration/social-bilibili-pipeline.test.js +0 -261
  150. package/__tests__/integration/wechat-bootstrap-end-to-end.test.js +0 -390
  151. package/__tests__/key-providers.test.js +0 -126
  152. package/__tests__/kg-derive.test.js +0 -219
  153. package/__tests__/llm-client.test.js +0 -122
  154. package/__tests__/longtail-adapters.test.js +0 -281
  155. package/__tests__/messaging-qq-snapshot.test.js +0 -294
  156. package/__tests__/mobile-extractor-encrypted.test.js +0 -460
  157. package/__tests__/mobile-extractor.test.js +0 -288
  158. package/__tests__/mock-adapter.test.js +0 -93
  159. package/__tests__/prompt-builder.test.js +0 -249
  160. package/__tests__/query-parser.test.js +0 -302
  161. package/__tests__/rag-derive.test.js +0 -169
  162. package/__tests__/registry-readiness.test.js +0 -292
  163. package/__tests__/registry.test.js +0 -420
  164. package/__tests__/salvage-ingest.test.js +0 -97
  165. package/__tests__/schemas.test.js +0 -331
  166. package/__tests__/shopping-adapters.test.js +0 -392
  167. package/__tests__/shopping-eleme-snapshot.test.js +0 -454
  168. package/__tests__/shopping-pinduoduo-snapshot.test.js +0 -484
  169. package/__tests__/shopping-snapshot.test.js +0 -438
  170. package/__tests__/shopping-vipshop-snapshot.test.js +0 -425
  171. package/__tests__/shopping-xianyu-snapshot.test.js +0 -451
  172. package/__tests__/sidecar-contacts-cross-validate.test.js +0 -186
  173. package/__tests__/sidecar-supervisor.test.js +0 -128
  174. package/__tests__/sign-providers.test.js +0 -62
  175. package/__tests__/social-adapters.test.js +0 -280
  176. package/__tests__/social-bilibili-snapshot.test.js +0 -278
  177. package/__tests__/social-douban-snapshot.test.js +0 -351
  178. package/__tests__/social-douyin-im-direct-read.test.js +0 -377
  179. package/__tests__/social-douyin-salvage-collector.test.js +0 -98
  180. package/__tests__/social-douyin-salvage-mapper.test.js +0 -90
  181. package/__tests__/social-douyin-snapshot.test.js +0 -256
  182. package/__tests__/social-kuaishou-snapshot.test.js +0 -362
  183. package/__tests__/social-toutiao-snapshot.test.js +0 -366
  184. package/__tests__/social-weibo-snapshot.test.js +0 -234
  185. package/__tests__/social-weibo-sqlite-device.test.js +0 -174
  186. package/__tests__/social-xiaohongshu-snapshot.test.js +0 -232
  187. package/__tests__/sqlite-leaf-salvage.test.js +0 -97
  188. package/__tests__/travel-adapters.test.js +0 -483
  189. package/__tests__/travel-maps-snapshot.test.js +0 -426
  190. package/__tests__/vault-driver-error.test.js +0 -74
  191. package/__tests__/vault-search-helpers.test.js +0 -104
  192. package/__tests__/vault-search.test.js +0 -423
  193. package/__tests__/vault.test.js +0 -767
  194. package/__tests__/wechat-adapter.test.js +0 -594
  195. package/__tests__/whatsapp-adapter.test.js +0 -138
  196. package/scripts/_make-fixture-all.js +0 -126
  197. package/scripts/_make-fixture-contacts.js +0 -84
  198. package/scripts/evaluate-entity-resolver.js +0 -213
  199. package/scripts/run-native-tests-sandbox.sh +0 -55
  200. package/scripts/smoke-phase-5-5.js +0 -196
  201. package/scripts/smoke-phase-5-7.js +0 -181
  202. package/scripts/smoke-system-data-contacts.js +0 -309
  203. package/scripts/smoke-system-data.js +0 -312
  204. package/vitest.config.js +0 -88
@@ -1,451 +0,0 @@
1
- "use strict";
2
-
3
- import { describe, it, expect, beforeEach } from "vitest";
4
-
5
- const fs = require("node:fs");
6
- const path = require("node:path");
7
- const os = require("node:os");
8
-
9
- const {
10
- XianyuAdapter,
11
- SNAPSHOT_SCHEMA_VERSION,
12
- VALID_SNAPSHOT_KINDS,
13
- orderToRecord,
14
- extractOrders,
15
- normSide,
16
- } = require("../lib/adapters/shopping-xianyu");
17
- const { assertAdapter } = require("../lib/adapter-spec");
18
- const { validateBatch } = require("../lib/batch");
19
-
20
- // 闲鱼 (Xianyu / goofish) — Alibaba C2C 二手交易; mirrors shopping-eleme with a
21
- // two-sided buy/sell `side`. mtop signing is injected (signProvider) so the
22
- // adapter stays pure-Node.
23
-
24
- function writeSnapshot(dir, snapshot) {
25
- const p = path.join(dir, "shopping-xianyu.json");
26
- fs.writeFileSync(p, JSON.stringify(snapshot), "utf-8");
27
- return p;
28
- }
29
-
30
- function writeRaw(dir, fileName, content) {
31
- const p = path.join(dir, fileName);
32
- fs.writeFileSync(p, content, "utf-8");
33
- return p;
34
- }
35
-
36
- describe("XianyuAdapter snapshot mode", () => {
37
- let tmpDir;
38
- beforeEach(() => {
39
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "xianyu-snap-"));
40
- });
41
-
42
- it("exports SNAPSHOT_SCHEMA_VERSION = 1 and VALID_SNAPSHOT_KINDS = [order]", () => {
43
- expect(SNAPSHOT_SCHEMA_VERSION).toBe(1);
44
- expect(VALID_SNAPSHOT_KINDS).toEqual(["order"]);
45
- });
46
-
47
- it("authenticate(inputPath) ok when readable", async () => {
48
- const p = writeSnapshot(tmpDir, { schemaVersion: 1, snapshottedAt: Date.now(), events: [] });
49
- const a = new XianyuAdapter();
50
- const res = await a.authenticate({ inputPath: p });
51
- expect(res.ok).toBe(true);
52
- expect(res.mode).toBe("snapshot-file");
53
- });
54
-
55
- it("authenticate(inputPath) fails when path unreadable", async () => {
56
- const a = new XianyuAdapter();
57
- const res = await a.authenticate({ inputPath: path.join(tmpDir, "missing.json") });
58
- expect(res.ok).toBe(false);
59
- expect(res.reason).toBe("INPUT_PATH_UNREADABLE");
60
- });
61
-
62
- it("authenticate() with no inputPath returns NO_INPUT", async () => {
63
- const a = new XianyuAdapter();
64
- const res = await a.authenticate({});
65
- expect(res.ok).toBe(false);
66
- expect(res.reason).toBe("NO_INPUT");
67
- expect(res.message).toMatch(/snapshot mode/);
68
- });
69
-
70
- it("sync() without inputPath throws with signing hint", async () => {
71
- const a = new XianyuAdapter();
72
- let threw = null;
73
- try {
74
- for await (const _r of a.sync({})) { /* drain */ }
75
- } catch (err) {
76
- threw = err;
77
- }
78
- expect(threw).toBeTruthy();
79
- expect(String(threw.message)).toMatch(/signProvider/);
80
- });
81
-
82
- it("rejects non-JSON inputPath", async () => {
83
- const p = writeRaw(tmpDir, "orders.html", "<html>not json</html>");
84
- const a = new XianyuAdapter();
85
- let threw = null;
86
- try {
87
- for await (const _r of a.sync({ inputPath: p })) { /* drain */ }
88
- } catch (err) {
89
- threw = err;
90
- }
91
- expect(threw).toBeTruthy();
92
- expect(String(threw.message)).toMatch(/snapshot must be JSON/);
93
- });
94
-
95
- it("rejects schemaVersion mismatch", async () => {
96
- const p = writeSnapshot(tmpDir, { schemaVersion: 99, snapshottedAt: Date.now(), events: [] });
97
- const a = new XianyuAdapter();
98
- let threw = null;
99
- try {
100
- for await (const _r of a.sync({ inputPath: p })) { /* drain */ }
101
- } catch (err) {
102
- threw = err;
103
- }
104
- expect(threw).toBeTruthy();
105
- expect(String(threw.message)).toMatch(/schemaVersion mismatch/);
106
- });
107
-
108
- it("empty events array yields nothing (no crash)", async () => {
109
- const p = writeSnapshot(tmpDir, { schemaVersion: 1, snapshottedAt: Date.now(), events: [] });
110
- const a = new XianyuAdapter();
111
- const raws = [];
112
- for await (const r of a.sync({ inputPath: p })) raws.push(r);
113
- expect(raws.length).toBe(0);
114
- });
115
-
116
- it("buy order round-trips normalize cleanly (counterparty = seller)", async () => {
117
- const now = Date.now();
118
- const p = writeSnapshot(tmpDir, {
119
- schemaVersion: 1,
120
- snapshottedAt: now,
121
- vendor: "xianyu",
122
- account: { userId: "u-alice", displayName: "alice" },
123
- events: [
124
- {
125
- kind: "order",
126
- id: "order-XY-9001",
127
- capturedAt: now - 1000,
128
- orderId: "XY-9001",
129
- side: "buy",
130
- title: "二手 iPhone 13 128G",
131
- counterparty: "卖家阿强",
132
- placedAt: now - 86400_000,
133
- paidAt: now - 86400_000 + 5_000,
134
- status: "交易成功",
135
- totalAmount: { value: 2800.0, currency: "CNY" },
136
- recipient: "张三",
137
- shippingAddress: "上海市浦东新区...",
138
- },
139
- ],
140
- });
141
- const a = new XianyuAdapter();
142
- const raws = [];
143
- for await (const r of a.sync({ inputPath: p })) raws.push(r);
144
- expect(raws.length).toBe(1);
145
- expect(raws[0].originalId).toBe("xianyu:order:order-XY-9001");
146
-
147
- const batch = a.normalize(raws[0]);
148
- expect(validateBatch(batch).valid).toBe(true);
149
- expect(batch.events.length).toBeGreaterThan(0);
150
- expect(JSON.stringify(batch)).toContain("二手 iPhone 13 128G");
151
- expect(JSON.stringify(batch)).toContain("卖家阿强");
152
- expect(JSON.stringify(batch)).toContain("delivered");
153
- });
154
-
155
- it("sell order maps side=sell into the record", async () => {
156
- const now = Date.now();
157
- const p = writeSnapshot(tmpDir, {
158
- schemaVersion: 1,
159
- snapshottedAt: now,
160
- events: [
161
- {
162
- kind: "order", id: "XY-SELL-1", orderId: "XY-SELL-1", side: "sell",
163
- title: "出闲置耳机", counterparty: "买家小李",
164
- placedAt: now, paidAt: now, status: "已完成",
165
- totalAmount: { value: 120, currency: "CNY" },
166
- },
167
- ],
168
- });
169
- const a = new XianyuAdapter();
170
- const raws = [];
171
- for await (const r of a.sync({ inputPath: p })) raws.push(r);
172
- const batch = a.normalize(raws[0]);
173
- expect(validateBatch(batch).valid).toBe(true);
174
- expect(JSON.stringify(batch)).toContain("sell");
175
- expect(JSON.stringify(batch)).toContain("买家小李");
176
- });
177
-
178
- it("status mapping handles xianyu-typical strings", async () => {
179
- const now = Date.now();
180
- const cases = [
181
- { status: "已发货", expect: "shipped" },
182
- { status: "待收货", expect: "shipped" },
183
- { status: "交易成功", expect: "delivered" },
184
- { status: "已完成", expect: "delivered" },
185
- { status: "退款成功", expect: "refunded" },
186
- { status: "已关闭", expect: "cancelled" },
187
- { status: "等待付款", expect: "placed" },
188
- ];
189
- for (const c of cases) {
190
- const p = writeSnapshot(tmpDir, {
191
- schemaVersion: 1,
192
- snapshottedAt: now,
193
- events: [
194
- { kind: "order", id: `o-${c.status}`, orderId: `o-${c.status}`, side: "buy",
195
- title: "x", counterparty: "c", placedAt: now, paidAt: now, status: c.status,
196
- totalAmount: { value: 1, currency: "CNY" } },
197
- ],
198
- });
199
- const a = new XianyuAdapter();
200
- const raws = [];
201
- for await (const r of a.sync({ inputPath: p })) raws.push(r);
202
- const batch = a.normalize(raws[0]);
203
- expect(JSON.stringify(batch)).toContain(c.expect);
204
- }
205
- });
206
-
207
- it("respects per-kind include opt-out", async () => {
208
- const now = Date.now();
209
- const p = writeSnapshot(tmpDir, {
210
- schemaVersion: 1,
211
- snapshottedAt: now,
212
- events: [
213
- { kind: "order", id: "o1", orderId: "o1", side: "buy", title: "t", placedAt: now,
214
- totalAmount: { value: 1, currency: "CNY" } },
215
- ],
216
- });
217
- const a = new XianyuAdapter();
218
- const raws = [];
219
- for await (const r of a.sync({ inputPath: p, include: { order: false } })) raws.push(r);
220
- expect(raws.length).toBe(0);
221
- });
222
-
223
- it("respects opts.limit", async () => {
224
- const now = Date.now();
225
- const events = Array.from({ length: 5 }, (_, i) => ({
226
- kind: "order", id: `o${i}`, orderId: `o${i}`, side: "buy", title: "t",
227
- placedAt: now - i * 1000, totalAmount: { value: 1, currency: "CNY" },
228
- }));
229
- const p = writeSnapshot(tmpDir, { schemaVersion: 1, snapshottedAt: now, events });
230
- const a = new XianyuAdapter();
231
- const raws = [];
232
- for await (const r of a.sync({ inputPath: p, limit: 2 })) raws.push(r);
233
- expect(raws.length).toBe(2);
234
- });
235
-
236
- it("filters out unknown kinds (forward compat)", async () => {
237
- const now = Date.now();
238
- const p = writeSnapshot(tmpDir, {
239
- schemaVersion: 1,
240
- snapshottedAt: now,
241
- events: [
242
- { kind: "order", id: "o1", orderId: "o1", side: "buy", title: "t", placedAt: now,
243
- totalAmount: { value: 1, currency: "CNY" } },
244
- { kind: "message", id: "m1" },
245
- { kind: "future-kind", id: "x" },
246
- ],
247
- });
248
- const a = new XianyuAdapter();
249
- const raws = [];
250
- for await (const r of a.sync({ inputPath: p })) raws.push(r);
251
- expect(raws.length).toBe(1);
252
- expect(raws[0].kind).toBe("order");
253
- });
254
-
255
- it("snapshottedAt fallback when event capturedAt missing", async () => {
256
- const ts = 1700000000000;
257
- const p = writeSnapshot(tmpDir, {
258
- schemaVersion: 1,
259
- snapshottedAt: ts,
260
- events: [
261
- { kind: "order", id: "o1", orderId: "o1", side: "buy", title: "t",
262
- totalAmount: { value: 1, currency: "CNY" } },
263
- ],
264
- });
265
- const a = new XianyuAdapter();
266
- const raws = [];
267
- for await (const r of a.sync({ inputPath: p })) raws.push(r);
268
- expect(raws[0].capturedAt).toBe(ts);
269
- });
270
-
271
- it("advertises both snapshot and cookie-api capabilities", () => {
272
- const a = new XianyuAdapter();
273
- expect(a.capabilities).toContain("sync:snapshot");
274
- expect(a.capabilities).toContain("sync:cookie-api");
275
- expect(assertAdapter(a).ok).toBe(true);
276
- });
277
- });
278
-
279
- describe("XianyuAdapter cookie-api mode", () => {
280
- it("authenticate(cookie) ok when userId + cookies present", async () => {
281
- const a = new XianyuAdapter({ account: { userId: "u-1", cookies: "_m_h5_tk=ok" } });
282
- const res = await a.authenticate();
283
- expect(res.ok).toBe(true);
284
- expect(res.mode).toBe("cookie");
285
- expect(res.account).toBe("u-1");
286
- });
287
-
288
- it("authenticate(cookie) requires account.userId", async () => {
289
- const a = new XianyuAdapter({ account: { cookies: "_m_h5_tk=ok" } });
290
- const res = await a.authenticate();
291
- expect(res.ok).toBe(false);
292
- expect(res.reason).toBe("NO_ACCOUNT_USER_ID");
293
- });
294
-
295
- it("sync yields normalized buy+sell records from fetchFn fixture", async () => {
296
- const byTab = {
297
- buy: [
298
- { order_id: "XY-BUY-1", title: "二手相机", seller_nick: "卖家A", status_text: "交易成功",
299
- total_amount: 1500, order_time: 1700000000, pay_time: 1700000010,
300
- receiver: "李四", address: "广州..." },
301
- ],
302
- sell: [
303
- { order_id: "XY-SELL-1", title: "出旧书", buyer_nick: "买家B", status_text: "交易成功",
304
- total_amount: 30, order_time: 1700000500 },
305
- ],
306
- };
307
- const fetchFn = async (opts) => ({ orders: byTab[opts.query.tab] || [] });
308
- const a = new XianyuAdapter({ account: { userId: "u-1", cookies: "_m_h5_tk=ok" }, fetchFn });
309
- const raws = [];
310
- for await (const r of a.sync({ sinceWatermark: 0 })) raws.push(r);
311
- expect(raws.map((r) => r.originalId).sort()).toEqual(["XY-BUY-1", "XY-SELL-1"]);
312
- const buy = raws.find((r) => r.originalId === "XY-BUY-1");
313
- expect(buy.payload.record.extras.side).toBe("buy");
314
- expect(buy.payload.record.merchantName).toBe("卖家A");
315
- expect(buy.payload.record.totalAmount.value).toBe(1500);
316
- expect(buy.payload.record.status).toBe("delivered");
317
- const sell = raws.find((r) => r.originalId === "XY-SELL-1");
318
- expect(sell.payload.record.extras.side).toBe("sell");
319
- expect(sell.payload.record.merchantName).toBe("买家B");
320
-
321
- const batch = a.normalize(buy);
322
- expect(validateBatch(batch).valid).toBe(true);
323
- expect(JSON.stringify(batch)).toContain("二手相机");
324
- });
325
-
326
- it("invokes signProvider and passes sign to fetchFn", async () => {
327
- let seenSign = null;
328
- const signProvider = async () => "SIGN-XYZ";
329
- const fetchFn = async (opts) => {
330
- seenSign = opts.sign;
331
- return { orders: [] };
332
- };
333
- const a = new XianyuAdapter({
334
- account: { userId: "u-1", cookies: "_m_h5_tk=ok" },
335
- fetchFn,
336
- signProvider,
337
- });
338
- for await (const _r of a.sync({ sinceWatermark: 0, sides: ["buy"] })) { /* drain */ }
339
- expect(seenSign).toBe("SIGN-XYZ");
340
- });
341
-
342
- it("passes sign: null when no signProvider configured", async () => {
343
- let seen = "unset";
344
- const fetchFn = async (opts) => {
345
- seen = opts.sign;
346
- return { orders: [] };
347
- };
348
- const a = new XianyuAdapter({ account: { userId: "u-1", cookies: "_m_h5_tk=ok" }, fetchFn });
349
- for await (const _r of a.sync({ sinceWatermark: 0, sides: ["buy"] })) { /* drain */ }
350
- expect(seen).toBe(null);
351
- });
352
-
353
- it("paginates and stops at sinceWatermark within one side", async () => {
354
- const pages = {
355
- 1: [
356
- { order_id: "p1-a", title: "t", order_time: 1700000000, total_amount: 10 },
357
- { order_id: "p1-b", title: "t", order_time: 1699000000, total_amount: 10 },
358
- ],
359
- 2: [{ order_id: "p2-a", title: "t", order_time: 1698000000, total_amount: 10 }],
360
- };
361
- const seenPages = [];
362
- const fetchFn = async (opts) => {
363
- seenPages.push(opts.query.pageNumber);
364
- return { orders: pages[opts.query.pageNumber] || [] };
365
- };
366
- const a = new XianyuAdapter({ account: { userId: "u-1", cookies: "_m_h5_tk=ok" }, fetchFn });
367
- const raws = [];
368
- for await (const r of a.sync({ sinceWatermark: 1699500000 * 1000, pageSize: 2, sides: ["buy"] })) {
369
- raws.push(r);
370
- }
371
- expect(raws.map((r) => r.originalId)).toEqual(["p1-a"]);
372
- expect(seenPages).toEqual([1]);
373
- });
374
-
375
- it("respects per-kind include opt-out in cookie mode (no fetch)", async () => {
376
- let called = false;
377
- const fetchFn = async () => {
378
- called = true;
379
- return { orders: [] };
380
- };
381
- const a = new XianyuAdapter({ account: { userId: "u-1", cookies: "_m_h5_tk=ok" }, fetchFn });
382
- const raws = [];
383
- for await (const r of a.sync({ include: { order: false } })) raws.push(r);
384
- expect(raws.length).toBe(0);
385
- expect(called).toBe(false);
386
- });
387
-
388
- it("normSide canonicalizes buy/sell tokens", () => {
389
- expect(normSide("buy")).toBe("buy");
390
- expect(normSide("sell")).toBe("sell");
391
- expect(normSide("卖出")).toBe("sell");
392
- expect(normSide("我买到的")).toBe("buy");
393
- expect(normSide(null, { bizType: "sold" })).toBe("sell");
394
- expect(normSide(undefined, {})).toBe("buy"); // default
395
- });
396
-
397
- it("orderToRecord maps xianyu buy fields (counterparty=seller)", () => {
398
- const rec = orderToRecord({
399
- order_id: "XY-9",
400
- title: "二手键盘",
401
- seller_nick: "卖家C",
402
- status_text: "已完成",
403
- total_amount: 88.0,
404
- order_time: 1700000000,
405
- }, "buy");
406
- expect(rec.orderId).toBe("XY-9");
407
- expect(rec.merchantName).toBe("卖家C");
408
- expect(rec.status).toBe("delivered");
409
- expect(rec.totalAmount.value).toBe(88.0);
410
- expect(rec.items[0].name).toBe("二手键盘");
411
- expect(rec.extras.side).toBe("buy");
412
- expect(rec.extras.capturedBy).toBe("cookie-api");
413
- });
414
-
415
- it("extractOrders tolerates nested mtop response shapes", () => {
416
- expect(extractOrders({ orders: [1] })).toEqual([1]);
417
- expect(extractOrders({ order_list: [2] })).toEqual([2]);
418
- expect(extractOrders({ data: { orderList: [3] } })).toEqual([3]);
419
- expect(extractOrders({ data: { list: [4] } })).toEqual([4]);
420
- expect(extractOrders([5])).toEqual([5]);
421
- expect(extractOrders({})).toEqual([]);
422
- expect(extractOrders(null)).toEqual([]);
423
- });
424
-
425
- it("uses opts.ordersUrl override when provided", async () => {
426
- let seenUrl = null;
427
- const fetchFn = async (opts) => {
428
- seenUrl = opts.url;
429
- return { orders: [] };
430
- };
431
- const a = new XianyuAdapter({
432
- account: { userId: "u-1", cookies: "_m_h5_tk=ok" },
433
- fetchFn,
434
- ordersUrl: "https://custom.example/orders",
435
- });
436
- for await (const _r of a.sync({ sinceWatermark: 0, sides: ["buy"] })) { /* drain */ }
437
- expect(seenUrl).toBe("https://custom.example/orders");
438
- });
439
-
440
- it("default fetchFn throws a legible error when cookie mode used without injection", async () => {
441
- const a = new XianyuAdapter({ account: { userId: "u-1", cookies: "_m_h5_tk=ok" } });
442
- let threw = null;
443
- try {
444
- for await (const _r of a.sync({ sinceWatermark: 0 })) { /* drain */ }
445
- } catch (err) {
446
- threw = err;
447
- }
448
- expect(threw).toBeTruthy();
449
- expect(String(threw.message)).toMatch(/no fetchFn configured/);
450
- });
451
- });
@@ -1,186 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * Cross-validate that Persons produced by the Python sidecar's
5
- * `system.parse_contacts` method pass the hub-side UnifiedSchema validator.
6
- *
7
- * Without this test, sidecar and hub can drift silently: sidecar emits
8
- * fields the schema rejects, or skips required ones. Run against a real
9
- * sidecar subprocess + synthesized contacts2.db.
10
- */
11
-
12
- import { describe, it, expect, beforeAll, afterAll } from "vitest";
13
- import path from "node:path";
14
- import fs from "node:fs";
15
- import os from "node:os";
16
- import { spawnSync } from "node:child_process";
17
-
18
- const { SidecarSupervisor } = require("../lib/sidecar");
19
- const { validatePerson } = require("../lib/schemas");
20
- const Database = require("better-sqlite3-multiple-ciphers");
21
-
22
- const SIDECAR_ROOT = path.resolve(
23
- __dirname,
24
- "..",
25
- "..",
26
- "personal-data-hub-bridge",
27
- );
28
-
29
- let pythonAvailable = true;
30
- try {
31
- const probe = spawnSync(
32
- process.env.FORENSICS_BRIDGE_PYTHON || "python",
33
- ["--version"],
34
- { stdio: "ignore" },
35
- );
36
- if (probe.status !== 0) pythonAvailable = false;
37
- } catch (_err) {
38
- pythonAvailable = false;
39
- }
40
-
41
- // Probe bs3mc — fixture seeding opens an unencrypted SQLite file via
42
- // better-sqlite3-multiple-ciphers, which fails on dev boxes where the root
43
- // node_modules binding was compiled for Electron's NODE_MODULE_VERSION
44
- // instead of the host Node ABI. Skip cleanly when the native binding
45
- // can't load; CI Linux builds get a Node-ABI binary and runs the full path.
46
- let bs3mcAvailable = true;
47
- try {
48
- const probeDir = fs.mkdtempSync(path.join(os.tmpdir(), "bs3mc-contacts-probe-"));
49
- const probeDb = new Database(path.join(probeDir, "p.db"));
50
- probeDb.close();
51
- fs.rmSync(probeDir, { recursive: true, force: true });
52
- } catch (_err) {
53
- bs3mcAvailable = false;
54
- }
55
-
56
- // FTS5 sandbox runner: the relative path to personal-data-hub-bridge
57
- // resolves outside the temp tree. Without this gate the spawn fails with
58
- // ENOENT during beforeAll instead of skipping cleanly.
59
- const sidecarRootAvailable = fs.existsSync(SIDECAR_ROOT);
60
-
61
- const describePy =
62
- pythonAvailable && bs3mcAvailable && sidecarRootAvailable
63
- ? describe
64
- : describe.skip;
65
-
66
- function seedFixtureContactsDb(dbPath) {
67
- const db = new Database(dbPath);
68
- try {
69
- db.exec(`
70
- CREATE TABLE raw_contacts (
71
- _id INTEGER PRIMARY KEY,
72
- display_name TEXT,
73
- starred INTEGER DEFAULT 0,
74
- deleted INTEGER DEFAULT 0
75
- );
76
- CREATE TABLE mimetypes (
77
- _id INTEGER PRIMARY KEY,
78
- mimetype TEXT NOT NULL UNIQUE
79
- );
80
- CREATE TABLE data (
81
- _id INTEGER PRIMARY KEY,
82
- raw_contact_id INTEGER NOT NULL,
83
- mimetype_id INTEGER NOT NULL,
84
- data1 TEXT
85
- );
86
- `);
87
- const mimetypes = {
88
- "vnd.android.cursor.item/phone_v2": 5,
89
- "vnd.android.cursor.item/email_v2": 1,
90
- "vnd.android.cursor.item/organization": 4,
91
- "vnd.android.cursor.item/note": 10,
92
- };
93
- const insertMime = db.prepare(
94
- "INSERT INTO mimetypes (_id, mimetype) VALUES (?, ?)",
95
- );
96
- for (const [mt, mid] of Object.entries(mimetypes)) insertMime.run(mid, mt);
97
-
98
- const insertContact = db.prepare(
99
- "INSERT INTO raw_contacts (_id, display_name, starred, deleted) VALUES (?, ?, ?, 0)",
100
- );
101
- insertContact.run(1, "妈妈", 1);
102
- insertContact.run(2, "张三", 0);
103
-
104
- const insertData = db.prepare(
105
- "INSERT INTO data (raw_contact_id, mimetype_id, data1) VALUES (?, ?, ?)",
106
- );
107
- insertData.run(1, mimetypes["vnd.android.cursor.item/phone_v2"], "13800001111");
108
- insertData.run(1, mimetypes["vnd.android.cursor.item/phone_v2"], "13900002222");
109
- insertData.run(1, mimetypes["vnd.android.cursor.item/email_v2"], "mom@example.com");
110
- insertData.run(2, mimetypes["vnd.android.cursor.item/phone_v2"], "13711112222");
111
- } finally {
112
- db.close();
113
- }
114
- }
115
-
116
- describePy("sidecar.system.parse_contacts × hub.validatePerson", () => {
117
- let supervisor;
118
- let tmpDir;
119
- let dbPath;
120
-
121
- beforeAll(async () => {
122
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "phdb-sidecar-contacts-"));
123
- dbPath = path.join(tmpDir, "contacts2.db");
124
- seedFixtureContactsDb(dbPath);
125
-
126
- supervisor = new SidecarSupervisor({
127
- command: process.env.FORENSICS_BRIDGE_PYTHON || "python",
128
- args: ["-u", "-m", "forensics_bridge.ipc_server"],
129
- cwd: SIDECAR_ROOT,
130
- healthCheckIntervalMs: 0,
131
- env: { PYTHONPATH: SIDECAR_ROOT },
132
- });
133
- await supervisor.start({ readyTimeoutMs: 8_000 });
134
- }, 15_000);
135
-
136
- afterAll(async () => {
137
- if (supervisor) await supervisor.stop({ graceMs: 1500 });
138
- if (tmpDir) {
139
- try {
140
- fs.rmSync(tmpDir, { recursive: true, force: true });
141
- } catch (_err) {
142
- /* best effort */
143
- }
144
- }
145
- });
146
-
147
- it("emits Persons that pass hub UnifiedSchema validation", async () => {
148
- const persons = [];
149
- const result = await supervisor.invoke(
150
- "system.parse_contacts",
151
- { data_path: dbPath, device_serial: "24115RA8EC-test" },
152
- {
153
- timeoutMs: 10_000,
154
- onChunk: (batch) => {
155
- for (const p of batch.persons || []) persons.push(p);
156
- },
157
- },
158
- );
159
-
160
- expect(result.status).toBe("ok");
161
- expect(result.totalPersons).toBe(2);
162
- expect(persons).toHaveLength(2);
163
-
164
- for (const person of persons) {
165
- const validation = validatePerson(person);
166
- if (!validation.valid) {
167
- // Dump the offender so CI failures are debuggable without re-running.
168
- console.error(
169
- "validatePerson failed for",
170
- JSON.stringify(person, null, 2),
171
- "errors:",
172
- validation.errors,
173
- );
174
- }
175
- expect(validation.valid).toBe(true);
176
- expect(validation.errors).toEqual([]);
177
- }
178
-
179
- // Spot-check shape — mom has phones+email+starred+notes? (notes none in this fixture)
180
- const mom = persons.find((p) => p.names[0] === "妈妈");
181
- expect(mom.identifiers.phone).toEqual(["13800001111", "13900002222"]);
182
- expect(mom.identifiers.email).toEqual(["mom@example.com"]);
183
- expect(mom.extra.starred).toBe(true);
184
- expect(mom.extra.deviceSerial).toBe("24115RA8EC-test");
185
- });
186
- });